gpt4 book ai didi

Java程序无限循环,没有任何错误信息

转载 作者:行者123 更新时间:2023-12-01 18:01:38 28 4
gpt4 key购买 nike

这里我正在学习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 操作系统引起的?希望有人帮助我吗?

最佳答案

这是因为您的测试 Thread.activeCount() > 1 永远不会是 false,因为您至少有 2 个线程仍将在同一个线程中运行/Activity 线程死亡后的线程组,它们是:

  1. 线程(当前线程)
  2. 监视 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);
}

关于Java程序无限循环,没有任何错误信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40505254/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com