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?}});
}根据乔恩的回答,这是行不通的,因为i没有被声明为final。
发布于 2012-12-17 08:19:25
不,run方法从来没有任何参数。您需要将初始状态放入Runnable。如果您使用的是匿名内部类,则可以通过最后一个局部变量执行此操作:
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
}
});
}发布于 2012-12-17 08:36:26
您可以创建接受参数的自定义线程对象,例如:
public class IndexedThread implements Runnable {
private final int index;
public IndexedThread(int index) {
this.index = index;
}
public void run() {
// ...
}
}可以这样使用:
IndexedThread threads[] = new IndexedThread[N];
for (int i=0; i<threads.length; i++) {
threads[i] = new IndexedThread(i);
}https://stackoverflow.com/questions/13910512
复制相似问题