我在这里学习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引起的?希望有人帮助我?
答案 0 :(得分:4)
这是因为您的测试Thread.activeCount() > 1
将永远不会是false
,因为您的线程在线程消失后至少有2个线程仍然在同一组线程中运行/活动,这些线程是:< / p>
main
主题(当前主题)Monitor Ctrl-Break
主题您可以通过调用Thread.currentThread().getThreadGroup().list()
来检查它,以打印当前线程组中所有线程的列表,所以更糟糕的是它应该是Thread.activeCount() > 2
。
但无论如何依靠Thread.activeCount()
它不可靠这样的事情并不是一个好习惯,因为它只是一个估算值,你应该使用{{3将你的线程同步为下一个:
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);
}