将runnable传递给Thread - Java

时间:2014-08-08 00:59:28

标签: java multithreading

我正在尝试以三种Runnable运行threads个对象。 Swing EDTcurrent thread(创建对象的线程)和main thread

到目前为止,我已经迈出了这一步:

public class MyExecutor implements Executor {

    public final static int SWING_MAIN_THREAD = 0;
    public final static int MAIN_THREAD = 1;
    public final static int RUNNING_THREAD = 2;

    private int threadType = -1;

    public MyExecutor (int threadType) {
        this.threadType = threadType;
    }

    @Override 
    public void execute(Runnable runnable) {
        switch(threadType) {
            case SWING_MAIN_THREAD:
                SwingUtilities.invokeLater(runnable);
                break;
            case MAIN_THREAD:
                // pass the runnable to the main thread
                // if main thread is the EDT, pass the runnable to the EDT
                // if main thread is a "normal" thread, pass the runnable to it
                break;
            case RUNNING_THREAD:
                // pass  the runnable to the thread that created this object
                break;
        }
    }

现在我遇到了MainThreadRunningThread案例,因为我无法找到将runnable对象传递给相应Thread的方法。我知道如何获取Thread,但我没有看到任何方法将runnable对象传递给它。

2 个答案:

答案 0 :(得分:4)

您可以使用SwingUtilities.invokeLater的主要原因是EDT有一个任务队列,其处理循环选择并运行任务,invokeLater只是将给定任务发布到该队列。

但是,大多数线程没有处理循环或任务队列,因此您无法将任务发布到任意线程。当然,您可以为线程编写这样的循环代码。

答案 1 :(得分:2)

您无法将对象传递给创建此对象的"线程,但您可以将其传递给调用execute()方法的线程,这将是正常的定义当前正在运行的线程

        case RUNNING_THREAD:
            // pass  the runnable to the thread that created this object
            runnable.run();
            break;

" main"线程在Java中不作为概念存在,对不起,你不能这样做。 (我的意思是主线程没有特别存储,所以你可以访问它。当然,它有一个主要的启动线程,但它并不特别。)

相关问题