[英]Java program keep infinite loop without any error message
在這里,我正在學習volatile
關鍵字和Java內存模型,代碼如下:
public class VolatileTest {
public volatile int inc = 0;
public void increase() {
inc++;
}
public static void main(String[] args) {
final VolatileTest test = new VolatileTest();
for(int i=0;i<10;i++){
new Thread(){
public void run() {
for(int j=0;j<10;j++)
test.increase();
};
}.start();
}
while(Thread.activeCount()>1)
Thread.yield();
System.out.println(test.inc);
}
}
怎么了 也許是由Mac OS引起的? 希望有人幫助我嗎?
這是因為您的測試Thread.activeCount() > 1
永遠不會為false
因為您至少有2個線程在線程死亡后仍在同一線程組中仍在運行/活動,它們是:
main
線程(當前線程) Monitor Ctrl-Break
線程 您可以通過調用Thread.currentThread().getThreadGroup().list()
以打印當前線程組中所有線程的列表,因此更糟糕的是,它應該是Thread.activeCount() > 2
。
但是無論如何,依賴Thread.activeCount()
並不是一個好習慣,因為它不可靠,因為它只是一個估計值,您應該寧願使用CountDownLatch
來同步線程,如下所示:
public static void main(String[] args) throws InterruptedException {
...
// CountDownLatch to be decremented 10 times to release awaiting threads
CountDownLatch latch = new CountDownLatch(10);
for(int i=0;i<10;i++){
new Thread(){
public void run() {
try {
...
} finally {
// Decrement it as the task is over
latch.countDown();
}
};
}.start();
}
// Await until the countdown reaches 0
latch.await();
System.out.println(test.inc);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.