检体执行服务如果线程花费太长时间,如何在执行程序服务中结束线程?
static class MyRunnable implements Runnable {
private String serverName;
public MyRunnable(String serverName) {
super();
this.serverName = serverName;
}
@Override
public void run() {
...
conn = new ch.ethz.ssh2.Connection(serverName);
conn.connect();
boolean isAuthenticated = conn.authenticateWithPassword(user, pass);
logger.info("Connecting to " + server);
if (isAuthenticated == false) {
logger.info(server + " Please check credentials");
}
sess = conn.openSession();
...
}
}
public static void main(String[] args) {
List<String> serverList = ...;
ExecutorService executor = Executors.newFixedThreadPool(20);
for (String serverName : serverList) {
MyRunnable r = new MyRunnable(serverName);
executor.execute(r);
}
executor.shutdown();
executor.awaitTermination(1, TimeUnit.HOURS);
}
就在这里是我的遗嘱执行人服务的示例代码。但有了这种逻辑,当我遇到无法连接的服务器或连接时间过长时,它会在我的应用程序中创建一个挂起时间。如果连接时间超过x时间,我想结束/终止线程。如果在2秒内没有连接到服务器,我该如何终止线程任务。
尝试
ThreadPoolExecutor executor = new ThreadPoolExecutor(
10, 25, 500, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(1));
添加以下代码,但显然如果超过2000毫秒时间越长,不结束线程。
尝试2
Future<?> future = executor.submit(new task));
try {
future.get(2000, TimeUnit.MILLISECONDS); // This waits timeout seconds; returns null
}
catch(TimeoutException e) {
future.cancel(true);
// System.out.println(server + "name");
}
关闭另一个线程的连接以导致Runnable中的异常。 – JimmyB
还有另一种使用超时的连接方法。 – assylias