Callable    call()方法有返回值,返回的是传入的类型的数据

FutureTask 有返回值,实现了runnableFuture接口,可以当做runnable来用,FutureTask 接收Callable类型的实例,包装成runnable类型,可以让线程执行

runnableFuture 继承了runnable和future接口,

FutureTask 既可以作为runnable交给线程来执行,也可以作为Future拿到任务的返回值

 

示例:

public class UseFuture {
	
	
	/*实现Callable接口,允许有返回值*/
	private static class UseCallable implements Callable<Integer>{
		private int sum;
		@Override
		public Integer call() throws Exception {
			System.out.println("Callable子线程开始计算!");  
//			Thread.sleep(1000);
	        for(int i=0 ;i<5000;i++){
	        	if(Thread.currentThread().isInterrupted()) {
					System.out.println("Callable子线程计算任务中断!");
					return null;
				}
	            sum=sum+i;
				System.out.println("sum="+sum);
	        }  
	        System.out.println("Callable子线程计算结束!结果为: "+sum);  
	        return sum; 
		}
	}
	
	public static void main(String[] args) 
			throws InterruptedException, ExecutionException {

		UseCallable useCallable = new UseCallable();
		//包装-->callable包装成FutureTask
		FutureTask<Integer> futureTask = new FutureTask<>(useCallable);
		Random r = new Random();
		//FutureTask交给线程来执行
		new Thread(futureTask).start();

		Thread.sleep(1);
		if(r.nextInt(100)>50){
			//futureTask.get()来拿到任务的结果,也可以终止任务,
			System.out.println("Get UseCallable result = "+futureTask.get());
		}else{
			System.out.println("Cancel................. ");
			//.cancel(true)方法其实是用了interrupt的中断,
			//必须在任务里添加线程中断标志位的验证才可以正常终止
			futureTask.cancel(true);
		}

	}

}

 

最后修改于 2019-09-06 22:30:03
如果觉得我的文章对你有用,请随意赞赏
扫一扫支付
上一篇