- get() 方法是阻塞得
- get(10,TimeUnit.SECONDS) get 的超时方法,线程里面并不会死掉
- isDone() 判断有没有做完
- cancel() 取消(代码里详细记录)
public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
//testInvokeAny();
testGet();
}
public static void testGet() throws ExecutionException, InterruptedException, TimeoutException {
ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
Future<Integer> future = threadPoolExecutor.submit(() -> {
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 10;
});
System.out.println("-------------------");
Thread callThread = Thread.currentThread();
new Thread(() -> {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 打断得是主线程
callThread.interrupt();
}).start();
// get 方法是阻塞得
//future.get(10,TimeUnit.SECONDS); // 这是带具有超时时间得获取(线程还未关闭线程)
Integer result = future.get();
System.out.println(result);
}
public static void testIsDone(){
ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) Executors.newCachedThreadPool(
new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.isDaemon();
return thread;
}
}
);
Future<Integer> future = threadPoolExecutor.submit(() -> {
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 10;
});
// 正常情况下,就是判断任务是否已经完成
// 异常情况下,出现问题也是 完成
System.out.println( future.isDone());
/**
* try to cancel fail
* 1: 任务已经完成
* 2:任务已经取消
*
* 取消任务方式 (取消了,拿不到值了)
* 1:配合
* while(!Thread.isTerrupted()){
*
* }
* 2: 比较流氓的方式 (让整个线程都死掉)
* new ThreadFactory() {
* @Override
* public Thread newThread(Runnable r) {
* Thread thread = new Thread(r);
* thread.isDaemon();
* return thread;
* }
* }
*
*/
boolean flag = future.cancel(true);
}