package cn.zq.test;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class OverTime {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ThreadPoolExecutor exec = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
Callable<String> doJob = new Callable<String>() {
@Override
public String call() throws Exception {
//开始执⾏耗时操作
Thread.sleep(1000 * 1);
return "线程执⾏完成.";
}
};
try {
Future<String> future = exec.submit(doJob);
String obj = future.get(1000 * 2, TimeUnit.MILLISECONDS); //任务处理超时时间设为 1 秒
System.out.println("任务成功返回:" + obj);
} catch (TimeoutException ex) {
System.out.println("处理超时啦....");
ex.printStackTrace();
} catch (Exception e) {
System.out.println("处理失败.");
e.printStackTrace();
}
// 关闭线程池
exec.shutdown();
}
}