将参数传递给 Java 线程

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13910512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 14:24:40  来源:igfitidea点击:

Passing parameter to Java Thread

javamultithreadingrunnable

提问by Terry Li

Thread t = new Thread(new Runnable() { public void run() {} });

I'd like to create a thread this way. How can I pass parameters to the runmethod if possible at all?

我想以这种方式创建一个线程。run如果可能,我如何将参数传递给方法?

Edit: To make my problem specific, consider the following code segment:

编辑:为了使我的问题具体,请考虑以下代码段:

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?}});
}

Based on Jon's answer it won't work, since iis not declared as final.

根据 Jon 的回答,它不起作用,因为i它没有被声明为final.

回答by Jon Skeet

No, the runmethod never has any parameters. You'll need to put the initial state into the Runnable. If you're using an anonymous inner class, you can do that via a final local variable:

不,该run方法从来没有任何参数。您需要将初始状态放入Runnable. 如果您使用的是匿名内部类,则可以通过最终局部变量来实现:

final int foo = 10; // Or whatever

Thread t = new Thread(new Runnable() {
    public void run() {
        System.out.println(foo); // Prints 10
    }
});

If you're writing a named class, add a field to the class and populate it in the constructor.

如果您正在编写命名类,请向该类添加一个字段并将其填充到构造函数中。

Alternatively, you may find the classes in java.util.concurrenthelp you more (ExecutorServiceetc) - it depends on what you're trying to do.

或者,您可能会发现这些课程对java.util.concurrent您有更多帮助(ExecutorService等)-这取决于您要尝试做什么。

EDIT: To put the above into your context, you just need a final variable within the loop:

编辑:要将上述内容放入您的上下文中,您只需要循环中的最终变量:

for (int i=0; i< threads.length; i++) {
    final int foo = i;
    threads[i] = new Thread(new Runnable() {
         public void run() {
             // Use foo here
         }
    });
}

回答by Frederik.L

You may create a custom thread object that accepts your parameter, for example :

您可以创建一个接受您的参数的自定义线程对象,例如:

public class IndexedThread implements Runnable {
    private final int index;

    public IndexedThread(int index) {
        this.index = index;
    }

    public void run() {
        // ...
    }
}

Which could be used like this :

可以这样使用:

IndexedThread threads[] = new IndexedThread[N];

for (int i=0; i<threads.length; i++) {
    threads[i] = new IndexedThread(i);
}