嗨,我是并发编程领域的新手,我正在测试下面的代码,似乎while循环没有终止线程.有人可以帮助解释这里发生的事情.
public class PrimePrinter{
public long counter = 0;
public synchronized long getCounter() {
return counter++;
}
public Thread makeThread() {
Runnable rn = new Runnable() {
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
while (counter < 100) {
try {
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + " : " +getCounter());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
return new Thread(rn);
}
public static void main(String[] args) {
int n = 10;
Thread[] threads = new Thread[10];
PrimePrinter pp = new PrimePrinter();
for(int i = 1; i < n; i++) {
threads[i] = pp.makeThread();
threads[i].start();
}
}
}
最后几行输出
Thread-4 : 81
Thread-5 : 87
Thread-7 : 91
Thread-5 : 97
Thread-2 : 95
Thread-4 : 98
Thread-6 : 96
Thread-8 : 90
Thread-1 : 93
Thread-3 : 92
Thread-0 : 94
Thread-2 : 99
Thread-6 : 107
Thread-3 : 103
Thread-0 : 104
Thread-1 : 105
Thread-8 : 106
Thread-5 : 102
Thread-4 : 101
Thread-7 : 100