关于java中的Runnable接口的问题?

Dav*_*vid 4 java multithreading

实现线程的一种方法是这样的:

  Runnable r1 = new Runnable() { 
    public void run() {
          // my code here
    }
  };  

  Thread thread1 = new Thread(r1);
  thread1.start();
Run Code Online (Sandbox Code Playgroud)

现在,如果我坚持使用这个简单的方法,那么无论如何都要从该线程外部传递一个运行块内的值.例如,我在运行中的代码包含一个逻辑,该逻辑需要来自将在调用时使用的进程的输出流.

如何将此流程流对象传递给此运行块.

我知道还有其他方法,比如实现runnable或extenting thread,但是你能告诉我如何使用上面的方法完成这个.

Lau*_*ves 5

您可以使用局部final变量:

final OutputStream stream = /* code that creates/obtains an OutputStream */

Runnable r1 = new Runnable() { 
  public void run() {
      // code that uses stream here
  }
};  

Thread thread1 = new Thread(r1);
thread1.start();
Run Code Online (Sandbox Code Playgroud)

final变量对匿名内部类是可见的,Runnable如上所述.

如果您的Runnable变得足够复杂,那么您应该考虑将其变为命名类.此时,构造函数参数通常是传递参数的最佳机制.