有人能告诉我如何将参数传递给线程吗?
另外,匿名类是如何工作的?
有人能告诉我如何将参数传递给线程吗?
另外,匿名类是如何工作的?
当前回答
参数通过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实现。在该类的构造函数中将参数传递给线程。
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类,并根据需要提供参数。文档中有一些简单的例子。我将把它们移植到这里:
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派生一个类,并在构造过程中(例如)传入参数。
然后使用Thread启动它。开始(Runnable r);
如果你的意思是在线程运行时,那么只需在调用线程中保持对派生对象的引用,并调用适当的setter方法(在适当的地方同步)。
有一种将参数传递到可运行程序的简单方法。 代码:
public void Function(final type variable) {
Runnable runnable = new Runnable() {
public void run() {
//Code adding here...
}
};
new Thread(runnable).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();