请考虑以下代码段:

如果在主线程中,我将其包含在方法中-

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();

最佳答案



不在局部变量上:它只是停止您重新分配该变量。



否。这是保证它的代码:

public static class ProcessThread implements Runnable {

    final CountDownLatch latch;

    // Plus the assignment in the constructor.

}

构造函数完成后,final字段将保证可见(正常情况下)。从JLS Sec 17.5:

10-05 19:02