当run()
方法在新线程中运行时,它将有自己的堆栈。countdown
不同堆栈中的 run 方法如何访问来自主线程的变量(如本例中的变量)?
final CountDownLatch countdown = new CountDownLatch(1);
for (int i = 0; i < 10; ++ i) {
Thread racecar = new Thread() {
public void run() {
countdown.await(); //all threads waiting
System.out.println("Vroom!");
}
};
racecar.start();
}
System.out.println("Go");
countdown.countDown();