1個線程輸出前100萬個素數(shù)庶诡,1個線程輸出前100萬個不能被3整除的數(shù)。
在兩個線程完成工作后停止時間計數(shù)器撼泛。
https://gist.github.com/augustrobo/7fd8a10f9116e29d726be26d649fbc3c
NumsFinder.java
啟動兩個線程茫船,以及時間計數(shù)。
public class NumsFinder {
public static void main(String[] args) {
int time = 0;
PrintNums t1 = new PrintNums("3");
t1.start();
PrintNums t2 = new PrintNums("prime");
t2.start();
while(true) {
System.out.println(time);
try{
Thread.sleep(1000);
} catch(InterruptedException exc) {
// do nothing
}
if (t1.isThreadOver() && t2.isThreadOver()) {
break;
}
time++;
}
System.out.println("\nTime elapsed: " + time + " seconds");
}
}
PrintNums.java
Thread的子類佣渴,根據(jù)不同的輸入num_type決定輸出是素數(shù)還是與num_type互素的數(shù)。
public class PrintNums extends Thread {
private String num_type;
private StringBuffer nums = new StringBuffer();
public PrintNums(String num_type) {
this.num_type = num_type;
}
public void run() {
int quantity = 1_000_000;
int num_cnt = 0;
if (num_type.equals("prime")) {
int candidate = 2;
nums.append("\nFirst ").append(quantity).append(" primes:\n\n");
while(num_cnt < quantity) {
if (isPrime(candidate)) {
nums.append(candidate).append(" ");
num_cnt++;
}
candidate++;
}
} else {
int candidate = 1;
int k = Integer.parseInt(num_type);
nums.append("\nFirst ").append(quantity).append(" relative prime to " + num_type + ":\n\n");
while(num_cnt < quantity) {
if (isRelativePrime(candidate, k)) {
nums.append(candidate).append(" ");
num_cnt++;
}
candidate++;
}
}
System.out.println(nums);
nums = null;
}
public static boolean isPrime(int checkNumber) {
double root = Math.sqrt(checkNumber);
for (int i = 2; i <= root; i++){
if (checkNumber % i == 0) {
return false;
}
}
return true;
}
public static boolean isRelativePrime(int checkNumber, int k) {
return checkNumber % k != 0;
}
public boolean isThreadOver() {
return nums == null;
}
}
運行結(jié)果如圖: