您的位置:首页 > 编程语言 > Java开发

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

2016-05-15 12:06 489 查看
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();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: