有人能告诉我如何将参数传递给线程吗?
另外,匿名类是如何工作的?
有人能告诉我如何将参数传递给线程吗?
另外,匿名类是如何工作的?
当前回答
要么编写一个实现Runnable的类,并在适当定义的构造函数中传递所需的任何内容,要么编写一个使用适当定义的构造函数来扩展Thread的类,该构造函数使用适当的参数调用super()。
其他回答
对于匿名类:
在这里回答问题编辑是如何工作的匿名类
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对象
您可以扩展Thread类或Runnable类,并根据需要提供参数。文档中有一些简单的例子。我将把它们移植到这里:
class PrimeThread extends Thread {
long minPrime;
PrimeThread(long minPrime) {
this.minPrime = minPrime;
}
public void run() {
// compute primes larger than minPrime
. . .
}
}
PrimeThread p = new PrimeThread(143);
p.start();
class PrimeRun implements Runnable {
long minPrime;
PrimeRun(long minPrime) {
this.minPrime = minPrime;
}
public void run() {
// compute primes larger than minPrime
. . .
}
}
PrimeRun p = new PrimeRun(143);
new Thread(p).start();
首先,我想指出其他答案都是正确的。 但是,在构造函数中使用形参可能对所有人来说都不是最好的主意。
在很多情况下,你会想要使用“匿名内部类”,并重写run()方法,因为为每个用途定义特定的类是很痛苦的。 (新MyRunnable(){…})
在创建Runnable时,参数可能无法在构造函数中传递。例如,如果你将这个对象传递给一个方法,这个方法将在单独的线程中执行一些工作,然后调用你的runnable,将该工作的结果应用到它。
在这种情况下,使用如下方法: public MyRunnable withParameter(对象参数),可能是更有用的选择。
我并不是说这是解决问题的最好办法,但它可以解决问题。
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();
}
我知道我迟到了几年,但我遇到了这个问题,并采取了一种非传统的方法。我想在不创建新类的情况下做到这一点,所以我想到了:
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();