考虑一下片段:
如果在主线程中,我把它放在方法中-
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是被允许的。和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();发布于 2016-10-10 07:18:58
最后保证初始化安全。
不在局部变量上:它只是阻止您重新分配该变量。
最后CountDownLatch闩锁=新的CountDownLatch(3); 上面的代码是否保证初始化,从而使锁存在下面的代码中完全可见?
不是的。正是这段代码保证了这一点:
public static class ProcessThread implements Runnable {
final CountDownLatch latch;
// Plus the assignment in the constructor.
}一旦构造函数完成(通常),final字段就保证是可见的。来自JLS第17.5节
当构造函数完成时,对象被认为是完全初始化的。只有在对象被完全初始化后才能看到对对象的引用的线程,保证看到该对象的
final字段的正确初始化值。
发布于 2016-10-10 07:15:03
局部变量驻留在堆栈上;当然,当您两次调用相同的方法时,它们在各自的堆栈上都有all --它们的局部变量。
只有当多个线程将写入相同的内存位置(堆上)时,才有意义。
这对于方法主体中的局部变量来说是完全没有意义的!
发布于 2016-10-10 07:52:34
您在本地执行的操作不会出现其他线程的可见性或干扰问题,因此声明局部变量易失性是没有意义的。
https://stackoverflow.com/questions/39952937
复制相似问题