有人能告诉我如何将参数传递给线程吗?

另外,匿名类是如何工作的?


当前回答

你需要在构造函数中将参数传递给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();

其他回答

对于匿名类:

在这里回答问题编辑是如何工作的匿名类

   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更好的解决方案。所以我更喜欢:

   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对象

你需要在构造函数中将参数传递给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();

有一种将参数传递到可运行程序的简单方法。 代码:

public void Function(final type variable) {
    Runnable runnable = new Runnable() {
        public void run() {
            //Code adding here...
        }
    };
    new Thread(runnable).start();
}

要创建线程,通常需要创建自己的Runnable实现。在该类的构造函数中将参数传递给线程。

class MyThread implements Runnable{
   private int a;
   private String b;
   private double c;

   public MyThread(int a, String b, double c){
      this.a = a;
      this.b = b;
      this.c = c;
   }

   public void run(){
      doSomething(a, b, c);
   }
}

在类中创建一个局部变量,用于扩展Thread或实现Runnable。

public class Extractor extends Thread {
    public String webpage = "";
    public Extractor(String w){
        webpage = w;
    }
    public void setWebpage(String l){
        webpage = l;
    }

    @Override
    public void run() {// l is link
        System.out.println(webpage);
    }
    public String toString(){
        return "Page: "+webpage;
    }}

通过这种方式,您可以在运行变量时传递变量。

Extractor e = new Extractor("www.google.com");
e.start();

输出:

"www.google.com"