Thread Timeout

package com.nantian.winUtliTest.ThreadTest;

import java.util.HashMap;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/ **
* Start a task, and then wait for the results of the task, if the wait time exceeds a pre-set timeout, the abort.
*
* @Author Chen Feng
* /
public class ThreadTest {

static void main public (String [] args) {
// System.out.println ( "Start ...");
//
// ExecutorService Exec = Executors.newCachedThreadPool (); // create a thread pool
//
// testTask (exec, 15); // task waits after a successful end results, without waiting 15 seconds ntaskResult: failReason to true: null
// TestTask (Exec,. 5); // wait only 5 seconds, the task is not over, so the task is terminated ntaskResult: null failReason: the main thread to wait for the results timeout, so the interrupt task thread!
//
// exec.shutdown ();
// System.out.println ( "End!");
}

the HashMap static public <String, String> TestTask (ExecutorService Exec, int timeout) {
// new new to MyTask Task to MyTask = ();
A = sA new new A ();
Future <the HashMap <String, String >> = exec.submit Future ( sA);

the HashMap <String, String> TaskResult = null;
String failReason = null;
the try {
// wait for the results, the maximum waiting timeout seconds, the second abort timeout
taskResult = future.get (timeout, TimeUnit.SECONDS) ;
the catch} (InterruptedException E) {
failReason = "main thread is interrupted while waiting for the results!";
} the catch (ExecutionException E) {
failReason = "main thread wait for the results, but the calculation thrown!";
} the catch (a TimeoutException E) {
failReason = "main thread wait for timeout calculations, so the interrupt task thread!";
exec.shutdownNow ();
}

System.out.println("ntaskResult : " + taskResult.get("isSucc"));
System.out.println("failReason : " + failReason);
return taskResult;
}
}

//class MyTask implements Callable<Boolean> {
//
// @Override
// public Boolean call() throws Exception {
// // 总计耗时约10秒
// for (int i = 0; i < 100L; i++) {
// Thread.sleep(100); // 睡眠0.1秒
// System.out.print('-');
// }
// return Boolean.TRUE;
// }
//}

Guess you like

Origin www.cnblogs.com/wzy-525/p/12059531.html