考虑片段:
如果在主线程中,我在方法中有这个-
volatile CountDownLatch latch = new CountDownLatch(3);
new Thread(new ProcessThread("Worker1",latch, 20000)).start();//20 secs
new Thread(new ProcessThread("Worker2",latch, 60000)).start();//60 secs
new Thread(new ProcessThread("Worker3",latch, 40000)).start();//40 secs
我看到 volatile
显示为非法修饰符。并且只允许使用 final
。 并最终保证初始化安全。
public static class ProcessThread implements Runnable {
final CountDownLatch latch;
final long workDuration;
final String name;
public ProcessThread(String name, CountDownLatch latch, long duration){
this.name= name;
this.latch = latch;
this.workDuration = duration;
}
}
下面的对象即 new CountDownLatch(3)
是正确构造的,但我还想确保上面对象分配给的引用 latch
保证对其下方的代码可见。
final CountDownLatch latch = new CountDownLatch(3);
上面的代码是否保证初始化,以便 latch
对下面的代码完全可见,即
new Thread(new ProcessThread("Worker1",latch, 20000)).start();
最佳答案
局部变量存在于栈中;当然,当您两次调用相同方法时,它们的所有局部变量都在各自的堆栈上。
volatile 仅在多个 线程写入相同 内存位置(在堆上)时才有意义。
这对于方法体内的局部变量完全没有意义!
关于java - 为什么局部变量不允许使用 volatile 关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39952937/