有人能告诉我如何将参数传递给线程吗?
另外,匿名类是如何工作的?
有人能告诉我如何将参数传递给线程吗?
另外,匿名类是如何工作的?
当前回答
参数通过start()和run()方法传递:
// Tester
public static void main(String... args) throws Exception {
ThreadType2 t = new ThreadType2(new RunnableType2(){
public void run(Object object) {
System.out.println("Parameter="+object);
}});
t.start("the parameter");
}
// New class 1 of 2
public class ThreadType2 {
final private Thread thread;
private Object objectIn = null;
ThreadType2(final RunnableType2 runnableType2) {
thread = new Thread(new Runnable() {
public void run() {
runnableType2.run(objectIn);
}});
}
public void start(final Object object) {
this.objectIn = object;
thread.start();
}
// If you want to do things like setDaemon(true);
public Thread getThread() {
return thread;
}
}
// New class 2 of 2
public interface RunnableType2 {
public void run(Object object);
}
其他回答
您可以从Runnable派生一个类,并在构造过程中(例如)传入参数。
然后使用Thread启动它。开始(Runnable r);
如果你的意思是在线程运行时,那么只需在调用线程中保持对派生对象的引用,并调用适当的setter方法(在适当的地方同步)。
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实现。在该类的构造函数中将参数传递给线程。
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);
}
}
我知道我迟到了几年,但我遇到了这个问题,并采取了一种非传统的方法。我想在不创建新类的情况下做到这一点,所以我想到了:
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();
要么编写一个实现Runnable的类,并在适当定义的构造函数中传递所需的任何内容,要么编写一个使用适当定义的构造函数来扩展Thread的类,该构造函数使用适当的参数调用super()。