概述:
main方法:主線程想做兩件事=兩個(gè)任務(wù):報(bào)名考試和買(mǎi)書(shū)
但是用一個(gè)Callable任務(wù)發(fā)起一個(gè)線程來(lái)做買(mǎi)書(shū)的任務(wù)-耗時(shí)7秒轴捎;
主線程自己完成報(bào)名考試的任務(wù)-耗時(shí)10秒悄谐;
package com.niewj.concurrent;
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;
/**
* Future和Callable例1
* @author weijun.nie
*
*/
public class ES_TPE_Test {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService executerService = Executors.newSingleThreadExecutor();
// 主線程要做兩件事:1.買(mǎi)書(shū); 2.報(bào)名考試
long start = System.currentTimeMillis();
// 1. 第一件事:買(mǎi)書(shū)
Future<Book> future = executerService.submit(new BuyBookTask()); // 定義了一個(gè)任務(wù):買(mǎi)書(shū)陵叽,需要一定的時(shí)間
executerService.shutdown();
// 2. 第一件事:報(bào)名考試 報(bào)名考試花費(fèi)10秒
for (int i = 1; i <= 10; i++) {
Thread.sleep(1000);
System.out.println("==== ==== 等報(bào)名排隊(duì)等了[ " + i + " ]天了 ==== ==== ");
}
Book book = future.get();
System.out.println("考試報(bào)上名了; 書(shū)也買(mǎi)到了: " + book);
long end = System.currentTimeMillis();
System.out.println("總耗時(shí)秒數(shù): " + (end - start) / 1000);
}
}
/**
* 購(gòu)買(mǎi)書(shū)籍任務(wù)-需要耗費(fèi)一定時(shí)間:假定買(mǎi)書(shū)需要等7天(一秒模擬一天)
*
* @author weijun.nie
*
*/
class BuyBookTask implements Callable<Book> {
final int restockDays = 7; // 等進(jìn)貨時(shí)間
@Override
public Book call() throws Exception {
for (int i = 1; i <= restockDays; i++) {
Thread.sleep(1000);
System.out.println("等書(shū)等了[ " + i + " ]天了。好啰。。数苫。。柱查。");
}
return new Book("稀缺書(shū)套裝", 120.5);
}
}
class Book {
private String name;
private Double price;
public Book(String name, Double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
if (this.name == null && this.price == null) {
return "沒(méi)有書(shū)!";
} else {
return name + " 這本書(shū) " + price + "元錢(qián)";
}
}
}