如何将参数传递给 Java 线程?

2022-08-31 04:57:24

任何人都可以向我建议如何将参数传递给线程?

另外,它如何适用于匿名类?


答案 1

您需要将构造函数中的参数传递给 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

对于匿名类:

为了回答问题编辑,这里是它如何为匿名类工作

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

这个答案基本上与这个类似的问题相同:如何将参数传递给Thread对象