考虑一下片段:
如果在主线程中,我将其放在method-
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();