有人能告诉我如何将参数传递给线程吗?

另外,匿名类是如何工作的?


当前回答

这个答案来得很晚,但也许有人会觉得它有用。它是关于如何在不声明命名类的情况下将参数传递给Runnable(对于内联程序来说很方便):

    String someValue = "Just a demo, really...";

    new Thread(new Runnable() {
        private String myParam;

        public Runnable init(String myParam) {
            this.myParam = myParam;
            return this;
        }

        @Override
        public void run() {
            System.out.println("This is called from another thread.");
            System.out.println(this.myParam);
        }
    }.init(someValue)).start();

当然,您可以将start的执行推迟到某个更方便或合适的时刻。这取决于你init方法的签名(所以它可能需要更多和/或不同的参数),当然甚至它的名字,但基本上你得到了一个想法。

事实上,还有另一种将参数传递给匿名类的方法,即使用初始化块。考虑一下:

    String someValue = "Another demo, no serious thing...";
    int anotherValue = 42;

    new Thread(new Runnable() {
        private String myParam;
        private int myOtherParam;
        // instance initializer
        {
            this.myParam = someValue;
            this.myOtherParam = anotherValue;
        }

        @Override
        public void run() {
            System.out.println("This comes from another thread.");
            System.out.println(this.myParam + ", " + this.myOtherParam);
        }
    }).start();

所有都发生在初始化程序块内部。

其他回答

通过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();
}

参数通过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);
}

不,你不能将参数传递给run()方法。签名告诉您(它没有参数)。可能最简单的方法是使用一个专门构建的对象,该对象接受构造函数中的形参并将其存储在final变量中:

public class WorkingTask implements Runnable
{
    private final Object toWorkWith;

    public WorkingTask(Object workOnMe)
    {
        toWorkWith = workOnMe;
    }

    public void run()
    {
        //do work
    }
}

//...
Thread t = new Thread(new WorkingTask(theData));
t.start();

一旦你这样做了-你必须小心你传递到“WorkingTask”的对象的数据完整性。数据现在将存在于两个不同的线程中,因此您必须确保它是线程安全的。

在类中创建一个局部变量,用于扩展Thread或实现Runnable。

public class Extractor extends Thread {
    public String webpage = "";
    public Extractor(String w){
        webpage = w;
    }
    public void setWebpage(String l){
        webpage = l;
    }

    @Override
    public void run() {// l is link
        System.out.println(webpage);
    }
    public String toString(){
        return "Page: "+webpage;
    }}

通过这种方式,您可以在运行变量时传递变量。

Extractor e = new Extractor("www.google.com");
e.start();

输出:

"www.google.com"

在Java 8中,你可以在并发API和ExecutorService中使用lambda表达式,作为直接使用线程的高级替代:

创建一个用于创建新线程的线程池 根据需要,但将重用之前构造的线程 可用。这些池通常会提高执行许多短期异步任务的程序的性能。

    private static final ExecutorService executor = Executors.newCachedThreadPool();

    executor.submit(() -> {
        myFunction(myParam1, myParam2);
    });

参见executors javadocs。