有人能告诉我如何将参数传递给线程吗?
另外,匿名类是如何工作的?
有人能告诉我如何将参数传递给线程吗?
另外,匿名类是如何工作的?
当前回答
您可以从Runnable派生一个类,并在构造过程中(例如)传入参数。
然后使用Thread启动它。开始(Runnable r);
如果你的意思是在线程运行时,那么只需在调用线程中保持对派生对象的引用,并调用适当的setter方法(在适当的地方同步)。
其他回答
您可以扩展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();
创建线程时,需要一个Runnable实例。传递形参最简单的方法是将它作为参数传递给构造函数:
public class MyRunnable implements Runnable {
private volatile String myParam;
public MyRunnable(String myParam){
this.myParam = myParam;
...
}
public void run(){
// do something with myParam here
...
}
}
MyRunnable myRunnable = new myRunnable("Hello World");
new Thread(myRunnable).start();
如果你想在线程运行时改变参数,你可以简单地给你的runnable类添加一个setter方法:
public void setMyParam(String value){
this.myParam = value;
}
一旦你有了这个,你可以通过像这样调用来改变参数的值:
myRunnable.setMyParam("Goodbye World");
当然,如果您希望在参数更改时触发一个操作,则必须使用锁,这使事情变得相当复杂。
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或Thread类的构造函数
class MyThread extends Thread {
private String to;
public MyThread(String to) {
this.to = to;
}
@Override
public void run() {
System.out.println("hello " + to);
}
}
public static void main(String[] args) {
new MyThread("world!").start();
}
你需要在构造函数中将参数传递给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();