问题

谁能告诉我如何将参数传递给线程?

此外,它如何为匿名类工作?


#1 热门回答(299 赞)

你需要将构造函数中的参数传递给Runnable对象:

public class MyRunnable implements Runnable {

   public MyRunnable(Object parameter) {
       // store parameter for later user
   }

   public void run() {
   }
}

并调用它:

Runnable r = new MyRunnable(param_value);
new Thread(r).start();

#2 热门回答(97 赞)

###对于匿名类:

在回答问题编辑时,这里是匿名类的工作原理

final X parameter = ...; // the final is important
   Thread t = new Thread(new Runnable() {
       p = parameter;
       public void run() { 
         ...
       };
   t.start();

###命名类:

你有一个扩展Thread(或实现Runnable)的类和一个带有你想要传递的参数的构造函数。然后,当你创建新线程时,你必须传入参数,然后启动线程,如下所示:

Thread t = new MyThread(args...);
t.start();

Runnable是比Thread BTW更好的解决方案。所以我更喜欢:

public class MyRunnable implements Runnable {
      private X parameter;
      public MyRunnable(X parameter) {
         this.parameter = parameter;
      }

      public void run() {
      }
   }
   Thread t = new Thread(new MyRunnable(parameter));
   t.start();

这个答案与这个类似的问题基本相同:How to pass parameters to a Thread object


#3 热门回答(34 赞)

通过Runnable或Thread类的构造函数

class MyThread extends Thread {

    private String to;

    public MyThread(String to) {
        this.to = to;
    }

    @Override
    public void run() {
        System.out.println("hello " + to);
    }
}

public static void main(String[] args) {
    new MyThread("world!").start();
}

原文链接