在不同的线程中启动不同的插件

时间:2015-12-22 04:19:35

标签: java multithreading parallel-processing threadpool

我有一个基础抽象类。有几个类从这个类扩展。这些可以指定为不同的插件。然后有一个主类使用反射启动这些插件。我需要在一个单独的线程中启动每个插件。下面是使用反射启动插件的行。

Class<?> c = cl.loadClass(className);
if (className.endsWith(currentPlugin.messageListner)) {
    // The MessageListner class found ...
    TestMessageListener messageListner = null;
    messageListner = (TestMessageListener) c.getConstructor(MessageBus.class, String.class)
            .newInstance(messageBus, currentPlugin.initParam);
    if (messageListner.start() == false) {
        currentPlugin.loadStatus = "failed";
        currentPlugin.errorCode = "Plugin start failed.";
    } else {
        currentPlugin.loadStatus = "success";
        currentPlugin.errorCode = "";
    }
    break;
}

所以我想把上面的代码段包装成一个线程,因为它将为每个插件执行(它在while循环中)。还有其他方法可以做到这一点吗?下面是我的基类的结构。

public abstract class TestMessageListener implements MessageListener {

    protected String initParam;

    protected int instanceId;

    public TestMessageListener(MessageBus messageBus, String initParam) {
        if (messageBus == null) {
            throw new NullPointerException();
        }
        this.messageBus = messageBus;
        this.initParam = initParam;
        String[] params = initParam.split(",");
        if ((params.length >= 1) && !params[0].isEmpty()) {
            // assign the first parameter as the instanceId
            instanceId = Integer.parseInt(params[0]);
        }
    }
    public abstract boolean start();
}

1 个答案:

答案 0 :(得分:1)

你可以试试这个:

 if (className.endsWith(currentPlugin.messageListner)) {
    new Thread(new Runnable() {

            @Override
            public void run() {
                //your thread code
                 TestMessageListener messageListner = null;
                    messageListner = (TestMessageListener) c.getConstructor(MessageBus.class, String.class)
                            .newInstance(messageBus, currentPlugin.initParam);
                    if (messageListner.start() == false) {
                        currentPlugin.loadStatus = "failed";
                        currentPlugin.errorCode = "Plugin start failed.";
                    } else {
                        currentPlugin.loadStatus = "success";
                        currentPlugin.errorCode = "";
                    }

            }
        }).start();//starting the thread
}