java thread问题的不解
近日在学习java thread,写了一个求素数的程序(其算法当然是不值一看的,只是为了学习)。
但结果颇感奇怪。小弟才疏学浅,不能明白了,还望赐教 :)
程序如下:
public class ThreadTester {
private static class WorkerThread extends Thread {
int count = 0;
public int currentMax = 2;
public boolean isEnd = true;
public WorkerThread() {
}
public void setCount(int i) {
this.count = i;
}
public void run() {
isEnd = false;
boolean prime = true;
for (int j = 2; j < count; j++) {
if (count % j == 0) {
prime = false;
break;
}
}
if (prime) {
currentMax = count;
}
isEnd = true;
}
}
public static void main(String[] args) {
int count = Integer.parseInt(args[0]);
WorkerThread w1 = new WorkerThread();
WorkerThread w2 = new WorkerThread();
WorkerThread w3 = new WorkerThread();
WorkerThread w4 = new WorkerThread();
int i = 3;
w1.start();
w2.start();
w3.start();
w4.start();
while (i < count-4) {
if (w1.isEnd) {
w1.setCount(i++);
w1.run();
}
if (w2.isEnd) {
w2.setCount(i++);
w2.run();
}
if (w3.isEnd) {
w3.setCount(i++);
w3.run();
}
if (w4.isEnd) {
w4.setCount(i++);
w4.run();
}
}
System.out.println(w1.currentMax);
System.out.println(w2.currentMax);
System.out.println(w3.currentMax);
System.out.println(w4.currentMax);
}
}
输入参数100,在我的pc上运算(win2000 prof,P4 1.7G)执行的结果是
83
2
97
2
也就是说有两个thread没有执行!
又换了台dell 6400(redhat linux server2.4,P3 至强 700×4)来执行,结果也差不多,还是感觉有两个thread没有执行。
而后又把参数调到1000000,执行了很久时间(算法很拙嘛~~)。执行过程中,一直top,发现并不是四个cpu都在running,结果也是有两个thread没有执行(输出为2)!
那位大虾解释一下。谢谢