概述:
main方法:主线程想做两件事=两个任务:报名考试和买书
但是用一个Callable任务发起一个线程来做买书的任务-耗时7秒;
主线程自己完成报名考试的任务-耗时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.买书; 2.报名考试
long start = System.currentTimeMillis();
// 1. 第一件事:买书
Future<Book> future = executerService.submit(new BuyBookTask()); // 定义了一个任务:买书,需要一定的时间
executerService.shutdown();
// 2. 第一件事:报名考试 报名考试花费10秒
for (int i = 1; i <= 10; i++) {
Thread.sleep(1000);
System.out.println("==== ==== 等报名排队等了[ " + i + " ]天了 ==== ==== ");
}
Book book = future.get();
System.out.println("考试报上名了; 书也买到了: " + book);
long end = System.currentTimeMillis();
System.out.println("总耗时秒数: " + (end - start) / 1000);
}
}
/**
* 购买书籍任务-需要耗费一定时间:假定买书需要等7天(一秒模拟一天)
*
* @author weijun.nie
*
*/
class BuyBookTask implements Callable<Book> {
final int restockDays = 7; // 等进货时间
@Override
public Book call() throws Exception {
for (int i = 1; i <= restockDays; i++) {
Thread.sleep(1000);
System.out.println("等书等了[ " + i + " ]天了。。。。。。");
}
return new Book("稀缺书套装", 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 "没有书!";
} else {
return name + " 這本書 " + price + "元錢";
}
}
}