Java并发-Future实例

1.  Main

public class Main {

	public static void main(String[] args) throws Exception {
		FutureContext futureContext = new FutureContext();
		
		ExecutorService executorService = Executors.newCachedThreadPool();
		for(int i = 0; i <= 9; i++) {
			Future<Integer> future = executorService.submit(new Worker(i * 10 + 1, i * 10 + 10));
			futureContext.addFuture(future);
		}
		executorService.shutdown();
		
		new Thread(new Consumer(futureContext)).start();
		System.out.println("Main thread finished.");
	}
}

 

2. Worker

public class Worker implements Callable<Integer> {
	private int start;
	private int end;
	
	public Worker(int start, int end) {
		this.start = start;
		this.end = end;
	}

	public Integer call() throws Exception {
		int sum = 0;
		for (int i = start; i <= end; i++) {
			sum += i;
		}
		System.out.println("Work[" + start + " , " + end + "], finished.");
		return sum;
	}
}

 

3. FutureContext

public class FutureContext {
	
	private List<Future<Integer>> futureList = new ArrayList<Future<Integer>>();

	public List<Future<Integer>> getFutureList() {
		return futureList;
	}

	public void addFuture(Future<Integer> future) {
		this.futureList.add(future);
	}
	
}

 

4. Consumer

public class Consumer implements Runnable {
	private FutureContext futureContext;
	
	public Consumer(FutureContext futureContext) {
		this.futureContext = futureContext;
	}
	
	public void run() {
		try{
			Thread.sleep(3000);
			
			int sum = 0;
			for(Future<Integer> fu : futureContext.getFutureList()) {
				sum += fu.get();
			}
			System.out.println("Three seconds later, Consumer finished, sum=" + sum);
		}catch(Exception e) {
			e.printStackTrace();
		}
	}

}

 

Console



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值