Thread t = new Thread(new Runnable() { public void run() {} });
我想用这种方式创建一个线程。如果可能,如何将参数传递给 run
方法?
编辑:为了使我的问题更具体,请考虑以下代码段:
for (int i=0; i< threads.length; i++) {
threads[i] = new Thread(new Runnable() {public void run() {//Can I use the value of i in the method?}});
}
根据 Jon 的回答,它不会起作用,因为 i
没有声明为 final
。
最佳答案
不,run
方法从来没有任何参数。您需要将初始状态放入 Runnable
。如果您使用的是匿名内部类,则可以通过 final 局部变量来实现:
final int foo = 10; // Or whatever
Thread t = new Thread(new Runnable() {
public void run() {
System.out.println(foo); // Prints 10
}
});
如果您正在编写命名类,请向该类添加一个字段并将其填充到构造函数中。
或者,您可能会发现 java.util.concurrent
中的类可以为您提供更多帮助(ExecutorService
等)- 这取决于您尝试做什么。
编辑:要将以上内容放入您的上下文中,您只需要循环中的最终变量:
for (int i=0; i< threads.length; i++) {
final int foo = i;
threads[i] = new Thread(new Runnable() {
public void run() {
// Use foo here
}
});
}
关于java - 将参数传递给 Java 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13910512/