gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 10:40:53 25 4
gpt4 key购买 nike

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

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

最佳答案

你可以试试这个:

 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
}

关于java - 在不同的线程中启动不同的插件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34408370/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com