线程之 Callable 和 Future

转载:https://www.cnblogs.com/dolphin0520/p/3949310.html

Runnable线程中只有一个无返回类型的run()方法,和Thread一样,执行完任务之后无法获取执行结果。
public interface Runnable { public abstract void run(); }

使用Callable会有返回类型,类型就是submit() 调用Callable()时 Future和FutureTask<>泛型中设置的类型。

public interface Callable<V> {
    V call() throws Exception;
}

暂时只需要知道Callable一般是和ExecutorService配合来使用的。

如:
{
	ExecutorService executor1 = Executors.newCachedThreadPool();
	executor1.submit(new FutureTask<Boolean>(new CaseClosedMailThread(location_id)));
	executor1.shutdown();
}
//在同一个文件中的外部类中:
class CaseClosedMailThread implements Callable<Boolean>{
	private String locationId;
	CaseClosedMailThread(String locationId){	//构造方法
		this.locationId=locationId;
	}
	@Override
	//重写call() 方法,和run()一样,只不过有返回值
	public Boolean call() throws Exception {
		//执行操作
	}
}

Future就是对于具体的Runnable或者Callable任务的执行结果进行取消、查询是否完成、获取结果。必要时可以通过get方法获取执行结果,该方法会阻塞直到任务返回结果。

public interface Future<V> {
    //有五个方法
}

Future提供了三种功能:
  1)判断任务是否完成;
  2)能够中断任务;
  3)能够获取任务执行结果。
  因为Future只是一个接口,所以是无法直接用来创建对象使用的,因此就有了下面的FutureTask。
  
我们先来看一下FutureTask的实现:

public class FutureTask<V> implements RunnableFuture<V>

//FutureTask类实现了RunnableFuture接口,我们看一下RunnableFuture接口的实现:
public interface RunnableFuture<V> extends Runnable, Future<V> {    
	void run();
}

可以看出RunnableFuture继承了Runnable接口和Future接口,而FutureTask实现了RunnableFuture接口。所以它既可以作为Runnable被线程执行,又可以作为Future得到Callable的返回值。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值