1.future應(yīng)用場景實際操作
- future 初步認(rèn)識 場景:假如你要做飯,啥也沒有。就得先買廚具跟食材
- 實現(xiàn)分析:網(wǎng)上買個廚具,然后快遞過來了,這期間你可以去買菜。所以可以在主線程(超市買菜)里面另起一個子線程去網(wǎng)購廚具 主線程與子線程異步執(zhí)行
- 等廚具來需要五分鐘,買菜需要兩分鐘。所以讓主線程去買菜,子線程去等廚具,主線程干完事就等著子線程。總之就是時間長那個交給異步future去做,時間短那個可以放主線程中執(zhí)行
- @author waw
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class SimpleTest {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
// 第一步 網(wǎng)購廚具
Callable<Chuju> onlineShopping = new Callable<Chuju>() {
public Chuju call() throws Exception {
System.out.println("下單 等待送貨...");
Thread.sleep(5000);// 模擬送貨時間
System.out.println("簽收 廚具送到...");
return new Chuju();
}
};
FutureTask<Chuju> task = new FutureTask<Chuju>(onlineShopping);
new Thread(task).start();
try {
// 第二步 去超時購買食材
Thread.sleep(2000);// 模擬購買食材時間
Shicai shicai = new Shicai();
System.out.println("食材到位...");
// 第三步 用網(wǎng)購來的廚具烹飪食材
if (!task.isDone()) {
System.out.println("廚具還沒到...");
}
Chuju chuju = task.get();
System.out.println("收到廚具 開始做飯...");
cook(chuju,shicai);
System.out.println("總共用時:" + (System.currentTimeMillis() - startTime));
} catch (Exception e) {
e.printStackTrace();
}
}
static void cook(Chuju chuju,Shicai shicai) {
System.out.println("做飯中...");
//do somthing
System.out.println("做飯結(jié)束...");
}
static class Chuju {
}
static class Shicai {
}
}