你的问题很有趣,我将程序改成下列形式: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;
System.out.println("COUNT="+count);
for (int j = 2; j < count; j++) {
if (count % j == 0) {
prime = false;
break;
}
System.out.print("j=" + j + "\t");
}
if (prime) {
currentMax = count;
}
System.out.println();
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) {
System.out.println("No." + i);
if (w1.isEnd) {
System.out.print("w1:" + i + "\t");
w1.setCount(i++);
w1.run();
}
if (w2.isEnd) {
System.out.print("w2:" + i + "\t");
w2.setCount(i++);
w2.run();
}
if (w3.isEnd) {
System.out.print("w3:" + i + "\t");
w3.setCount(i++);
w3.run();
}
if (w4.isEnd) {
System.out.print("w4:" + i + "\t");
w4.setCount(i++);
w4.run();
}
System.out.println();
}
System.out.println("w1" + w1.currentMax);
System.out.println("w2" + w2.currentMax);
System.out.println("w3" + w3.currentMax);
System.out.println("w4" + w4.currentMax);
}
}然后改命令行为
java ThreadTester 100 >result.txt
看文本文档中的内容,就会发现代码中的问题了。
在每次while的内部,四个进程都会被调用run方法,每次在这个方法返回后才继续执行代码。这也就得到了这个结果。这是因为你的w2和w4接收的数均为偶数,所以它们的currentMax不会发生改变。这并不是CPU的问题。但有一点要说清楚,就是创建线程和运行线程的方法,并不是调用Thread的run方法,而是Thread.start()。这个调用开动一个新的线程程序并执行它本身的run()方法,如果你统计一下result.txt中COUNT文字的个数,发现它是100个,这里面包括while循环中的3到98的96次调用run方法,和四次在w*.start()时调用的。关于线程类(Thread类),我们可以通过重载其run()方法,并调用Thread.start()来开启一个新的线程,这个方法是不需要等待run()方法的返回值的。而显式的调用run()方法则和一般的方法调用无差别,直到这个方法中的代码执行结束后这个方法才返回。呵呵,接分。