檢體執行服務如果線程花費太長時間,如何在執行程序服務中結束線程?
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