【编程题】利用多线程求解某范围素数,每个线程负责 1000范围:
线程1找1-1000;
线程 2 找 1001-2000;
线程 3 找 2001-3000。编程程序将每个线程找到的素数集中打印。
所有的素数输出完毕后,再输出素数的总数;
public class Test extends Thread {
private int beg;
private int end;
public static int count=0;
public Test(int beg, int end) {
super();
this.beg = beg;
this.end = end;
}
@Override
public void run() {
//如果是素数就输出
while(true){
if(beg>end){
return;
}
if(sushu(beg)){
System.out.println(beg);
count++;
}
beg++;
}
}
//方法判断
public boolean sushu(long beg){
if(beg == 2){
return true;
}
for(int i = 2 ;i<beg;i++){
if((beg % i)==0 ){
return false;
}
}
return true;
}
}
public class TestMain {
public static void main(String[] args) {
Test t1 = new Test(1,1000);
t1.start();
Test t2 = new Test(1001,2000);
t2.start();
Test t3 = new Test(2001,3000);
t3.start();
try {
//当前线程阻塞,直到另一个线程执行完,才能解除阻塞
t1.join();
t2.join();
t3.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("素数总数========"+Test.count);
}
}