先上一個場景:假如你忽然想作飯,可是沒有廚具,也沒有食材。網上購買廚具比較方便(慢),食材去超市買更放心(快)。java
實現分析:在快遞員送廚具的期間,咱們確定不會閒着,能夠去超市買食材。因此,在主線程裏面另起一個子線程去網購廚具。買好食材後,我就開始等待廚具到來。ide
FutureTask是Futura和Callable的組合體。Callable是一個支持返回值的Thread。this
package com.test;.net
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.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;線程
public class FutureCook {get
public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException {
ExecutorService exec = Executors.newCachedThreadPool(); //建立一個線程池
Future<String> hello = exec.submit(new Task("test"));
try {
System.out.println("11111111111");
System.out.println(hello.get(););
System.out.println(hello.get(1000l,TimeUnit.MILLISECONDS)); //經過調用Future的get方法,獲取線程的返回值
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println("22222222222");
long startTime = System.currentTimeMillis();
// 第一步 網購廚具
Callable<Chuju> onlineShopping = new Callable<Chuju>() {it
@Override
public Chuju call() throws Exception {
System.out.println("第一步:下單");
System.out.println("第一步:等待送貨");
Thread.sleep(5000); // 模擬送貨時間
System.out.println("第一步:快遞送到");
return new Chuju();
}
};
FutureTask<Chuju> task = new FutureTask<Chuju>(onlineShopping);
new Thread(task).start();
// 第二步 去超市購買食材
Thread.sleep(2000); // 模擬購買食材時間
Shicai shicai = new Shicai();
System.out.println("第二步:食材到位");
// 第三步 用廚具烹飪食材
if (!task.isDone()) { // 聯繫快遞員,詢問是否到貨
System.out.println("第三步:廚具還沒到,心情好就等着(心情很差就調用cancel方法取消訂單)");
}
Chuju chuju = task.get();
System.out.println("第三步:廚具到位,開始展示廚藝");
cook(chuju, shicai);
System.out.println("總共用時" + (System.currentTimeMillis() - startTime) + "ms");
}
// 用廚具烹飪食材
static void cook(Chuju chuju, Shicai shicai) {}
// 廚具類
static class Chuju {}
// 食材類
static class Shicai {}io
/**
* Created by yulinfeng on 12/17/16.
*/
public static class Task implements Callable<String> {
private String name;class
public Task(String name){
this.name = name;
}test
@Override
public String call() throws Exception {
Thread.sleep(2000);
String hello = hello(name);
return hello;
}
public String hello(String name){ return "hello " + name; } } }