Future 和 Callable
1.1 Callable 和 Runnable 的區別
1.Callable 接口的call()方法可以有返回值,而Runnable接口的run()方法沒有返回值。執行完Callable
接口中的任務後,返回值是通過接口進行獲得的。
2.Callable 接口的call()方法可以聲明拋出異常,而Runnale的接口run()方法不可以聲明拋出異常。
1.2 方法cancel(boolean b) 和 isCancelled()的使用
方法cancel(boolean b)的參數 b 的作用是:如果線程正在運行則是否中斷正在運行的線程,在代碼中使用if(Thread.currentThread().isInterrupted())
進行配合。
方法cancel()的返回值代表發送取消任務的命令是否成功完成
1.3 代碼
/**
* 方法 cancle(boolean mayInterruptIfRunning) 的參數 mayInterruptIfRunning的作用是:
* 如果線程正在運行則是否中斷正在運行的線程,
* 在代碼中使用if(Thread.currentThread().isInterrupted())進行配合。
* 方法 cancel()的返回值代表發送取消任務的命令是否成功完成
*/
package com.lhc.concurrent.future;
import java.util.concurrent.*;
public class MyCallable implements Callable{
@Override
public String call() throws Exception {
boolean bool = true;
while(bool){
if(Thread.currentThread().isInterrupted()){
throw new InterruptedException();
}
System.out.println("運行中");
}
return "hello world";
}
public static void main(String[] args) throws Exception{
MyCallable myCallable = new MyCallable();
ThreadPoolExecutor pool = new ThreadPoolExecutor(5, Integer.MAX_VALUE, 5,
TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>());
Future future = pool.submit(myCallable);
Thread.sleep(4000);
System.out.println("cancel:" + future.cancel(true) + ",isCancelled:" + future.isCancelled());
}
}
1.4 測試結果
…
運行中
運行中
運行中
運行中
運行中
運行中
cancel:true,isCancelled:true