java 线程池执行 callable 接口,future 接收callable 接口的返回值

callable 接口和runnable 接口的区别

(1)callable 和runnable 很像, callable 的call() 方法可以等同于runnable 的run() 方法,
(2)call() 能返回结果,run()不能。
(3)call() 可以抛出受检查的异常,比如ClassNotFoundException, 而run()不能抛出受检查的异常。

代码:

package ThreadPoolTest;

import java.util.ArrayList;
import java.util.List;
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;

/**
 * callable 和runnable 很像,callable 的call() 方法可以等同于runnable 的run() 方法,
 * 区别在于:
 * (1)call() 能返回结果,run()不能。
 * (2)call() 可以抛出受检查的异常,比如ClassNotFoundException, 而run()不能抛出受检查的异常。 
 * future 相当于容器,用于接收callable 执行后的结果
 * @author jalo
 *
 */
class CallableClass implements Callable<String> { //call()函数返回的类型,就是依赖于这个泛型,也就代表了future 的泛型类型
	
	int id ;
	public CallableClass(int id) {
		this.id = id;
	}
	@Override
	public String call() throws InterruptedException {
		Thread.sleep(2000);
		return "this task's result is " + id;
	}
}

public class CallableTest {
	public static void newCachedThreadPoolTest() throws InterruptedException, ExecutionException {
		ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
		List<Future<String>> callableTaskResultlist = new ArrayList<Future<String>>();
		for(int i=0;i<10;i++) {
			callableTaskResultlist.add(cachedThreadPool.submit(new CallableClass(i)));
			//System.out.println(cachedThreadPool.submit(new CallableClass(i)).get());//这样写,会block住,直到callable 出结果,才算这句结束
		}
		Thread.sleep(3000);//如果不加这句话,任务都没执行完。加了,都执行完了,说明上句就是提交个结果的引用给future,给了之后,结果随时可能发生变化
		for(Future<String> future : callableTaskResultlist) {
			if(future.isDone()) {
				System.out.println(future.get());
			} else {
				System.out.println("future result is not yet complete !");
			}
		}
	}
	
	public static void main(String[] args) throws InterruptedException, ExecutionException {
		newCachedThreadPoolTest();
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值