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

Starting different plugins in different threads

我有一个基础摘要class。有几个 class 是从这个 class 延伸出来的。这些可以指定为不同的插件。然后有一个 main class 使用反射启动这些插件。我需要在单独的线程中启动每个插件。下面是使用反射启动插件的行。

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 循环中)。还有其他方法可以做到这一点吗?下面是我的基础class.

的结构
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();
}

你可以试试这个:

 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
}