Future异步计算

个人认为,此处的异步计算指的是调用函数在持续监测Callable线程运算结果的同时可以处理其他事情,当Callable线程的运算结果满足条件了,调用函数再去处理与Callable线程相关的事情。就相当于触发机制,调用函数被Callable线程的运算结果触发。

摘抄自《编写高质量代码》的一个例子:

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;
public class Test {
	public static void main(String[] args) throws InterruptedException, ExecutionException{
		ExecutorService es=Executors.newSingleThreadExecutor();
		Tax t=new Tax(10000);
		Future<Integer> future=es.submit(t);
		while(future.isDone()==false){
			System.out.print("#");
			Thread.sleep(1000);
		}
		es.shutdown();
		System.out.println("\n结果:"+future.get());
	}
}
class Tax implements Callable<Integer>{
	private int money;
	public Tax(int money){
		this.money=money;
	}
	public Integer call() throws InterruptedException{
		Thread.sleep(10000);
		return money/34;
	}
}

这个在让main函数等待自定义线程上也很好用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值