execute():提交不需要返回值的任務,無法判斷任務是否被執行成功了。
submit():提交需要放回值的任務;線程會返回Future對象,通過Future的isDone()方法可以判斷任務是否執行成功,並且可以通過Future.get()獲取返回的值,get方法會阻塞,直到線程的完成
而get(long timeout, TimeUnit unit)會在等待一段時間後返回,這段時間內任務可能沒有執行完成。
以下是execute()和submit():使用的簡單demo
{
static class Customer extends Thread {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "開始執行");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
static class Home implements Callable {
int start;
int end;
public Home(int start, int end) {
this.start = start;
this.end = end;
}
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = start; i <=end; i++) {
sum+=i;
}
return sum;
}
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
ThreadPoolExecutor executor = new ThreadPoolExecutor(
10,
20,
20,
TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(10), new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
//1、設置線程的名字
Thread thread = new Thread(r);
//thread.setName("通過自定義線程工廠誰知線程名字");
//2、設置成守護線程
//thread.setDaemon(true);
return thread;
}
},
//四種阻塞隊列滿之後的處理方式
// new ThreadPoolExecutor.CallerRunsPolicy()); 使用調用線程處理,比如是main調用的線程池,用main線程執行
// new ThreadPoolExecutor.DiscardOldestPolicy());把阻塞隊列首元素丟掉,執行當前線程
// new ThreadPoolExecutor.DiscardPolicy());直接丟掉當前線程
new AbortPolicy());//跑出異常
executor.execute(new Customer());
//計算1加到30
Future submit1 = executor.submit(new Home(1,10));
//任務是否執行完成false
System.out.println(submit1.isDone());
Thread.sleep(100);
//任務是否執行完成true
System.out.println(submit1.isDone());
Future submit2 = executor.submit(new Home(11,20));
Future submit3 = executor.submit(new Home(21,30));
((Integer)submit1.get()).intValue();
System.out.println((((Integer)submit1.get()).intValue()+((Integer)submit2.get()).intValue()+((Integer)submit3.get()).intValue()));
}
}
結果
Thread-1開始執行
false
true
465