简体   繁体   English

如何运行不同线程的方法访问变量?

[英]How run method access variables of different Thread?

When run() method runs in new thread, it will have its own stack. run()方法在新线程中运行时,它将具有自己的堆栈。 How are the variables (like countdown in this case) from the main thread accessed by the run method in different stack? 如何通过不同堆栈中的run方法访问主线程中的变量(在这种情况下,如countdown )?

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

While each thread has its own stack, it shares the same heap with the rest of the program. 虽然每个线程都有自己的堆栈,但它与程序的其余部分共享相同的堆。 The normal class and variable scoping applies in that case since the run() method is in an anonymous inner class of the outer class, so it has access to the members of its host class. 在这种情况下,通常的类和变量作用域适用,因为run()方法位于外部类的匿名内部类中,因此它可以访问其宿主类的成员。

The countdown variable is not being pushed on the stack. countdown变量没有被压入堆栈。 If it was being passed as a parameter to the method then it would be pushed on the stack. 如果将其作为参数传递给方法,则将其压入堆栈。

Variables on the stack are local to the thread. 堆栈上的变量是线程本地的。 The stack and thread is support at the native level by the CPU and not a detail of Java. CPU在本机级别支持堆栈和线程,而不是Java的详细信息。

However, in your example, countdown is copied to a field on the sub-class of Thread you created, so it is a field of the object, not a stack local variable. 但是,在您的示例中, countdown被复制到您创建的Thread子类上的一个字段中,因此它是对象的一个​​字段,而不是堆栈局部变量。 (In fact you don't appear to have any) (实际上您似乎没有任何东西)

In byte code, it may use the stack, but once optimised, most likely it won't use the stack at all. 在字节码中,它可能会使用堆栈,但是一旦优化,很可能根本不会使用堆栈。 Instead registers are used. 而是使用寄存器。

The anonymous inner object is given a reference to the enclosing class behind the scenes. 匿名内部对象将获得对幕后封闭类的引用。

See here for an excellent Jon Skeet answer on the subject. 请参阅此处 ,以获取有关该主题的出色的Jon Skeet答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM