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

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


当前回答

Android专用

为了回调的目的,我通常使用输入参数实现自己的泛型Runnable:

public interface Runnable<TResult> {
    void run(TResult result);
}

用法很简单:

myManager.doCallbackOperation(new Runnable<MyResult>() {
    @Override
    public void run(MyResult result) {
        // do something with the result
    }
});

在经理:

public void doCallbackOperation(Runnable<MyResult> runnable) {
    new AsyncTask<Void, Void, MyResult>() {
        @Override
        protected MyResult doInBackground(Void... params) {
            // do background operation
            return new MyResult(); // return resulting object
        }

        @Override
        protected void onPostExecute(MyResult result) {
            // execute runnable passing the result when operation has finished
            runnable.run(result);
        }
    }.execute();
}

其他回答

这个答案来得很晚,但也许有人会觉得它有用。它是关于如何在不声明命名类的情况下将参数传递给Runnable(对于内联程序来说很方便):

    String someValue = "Just a demo, really...";

    new Thread(new Runnable() {
        private String myParam;

        public Runnable init(String myParam) {
            this.myParam = myParam;
            return this;
        }

        @Override
        public void run() {
            System.out.println("This is called from another thread.");
            System.out.println(this.myParam);
        }
    }.init(someValue)).start();

当然,您可以将start的执行推迟到某个更方便或合适的时刻。这取决于你init方法的签名(所以它可能需要更多和/或不同的参数),当然甚至它的名字,但基本上你得到了一个想法。

事实上,还有另一种将参数传递给匿名类的方法,即使用初始化块。考虑一下:

    String someValue = "Another demo, no serious thing...";
    int anotherValue = 42;

    new Thread(new Runnable() {
        private String myParam;
        private int myOtherParam;
        // instance initializer
        {
            this.myParam = someValue;
            this.myOtherParam = anotherValue;
        }

        @Override
        public void run() {
            System.out.println("This comes from another thread.");
            System.out.println(this.myParam + ", " + this.myOtherParam);
        }
    }).start();

所有都发生在初始化程序块内部。

还有一个选择;这种方法允许您像使用异步函数调用一样使用Runnable项。如果你的任务不需要返回一个结果,例如,它只是执行一些操作,你不需要担心如何传递回一个“结果”。

此模式允许您重用需要某种内部状态的项。当不在构造函数中传递参数时,需要注意调节程序对参数的访问。如果您的用例涉及不同的调用者,您可能需要更多的检查。

public class MyRunnable implements Runnable 
{
  private final Boolean PARAMETER_LOCK  = false;
  private X parameter;

  public MyRunnable(X parameter) {
     this.parameter = parameter;
  }

  public void setParameter( final X newParameter ){

      boolean done = false;
      synchronize( PARAMETER_LOCK )
      {
          if( null == parameter )
          {
              parameter = newParameter;
              done = true;
          }
      }
      if( ! done )
      {
          throw new RuntimeException("MyRunnable - Parameter not cleared." );
      }
  }


  public void clearParameter(){

      synchronize( PARAMETER_LOCK )
      {
          parameter = null;
      }
  }


  public void run() {

      X localParameter;

      synchronize( PARAMETER_LOCK )
      {
          localParameter = parameter;
      }

      if( null != localParameter )
      {
         clearParameter();   //-- could clear now, or later, or not at all ...
         doSomeStuff( localParameter );
      }

  }

}

线程=新的线程(新的MyRunnable(参数)); t.start ();

如果您需要处理的结果,您还需要在子任务完成时协调MyRunnable的完成。你可以传递一个回调或者只是等待线程't',等等。

对于匿名类:

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

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

我知道我迟到了几年,但我遇到了这个问题,并采取了一种非传统的方法。我想在不创建新类的情况下做到这一点,所以我想到了:

int x = 0;
new Thread((new Runnable() {
     int x;
     public void run() {
        // stuff with x and whatever else you want
     }
     public Runnable pass(int x) {
           this.x = x;
           return this;
     }
}).pass(x)).start();

从Java 8开始,您可以使用lambda来捕获有效的final参数。例如:

final String param1 = "First param";
final int param2 = 2;
new Thread(() -> {
    // Do whatever you want here: param1 and param2 are in-scope!
    System.out.println(param1);
    System.out.println(param2);
}).start();