runnable是执行工作的独立任务,但是它不返回任何值。如果要返回值,就需要用到callable,类型参数是泛型,参考下面的案例,返回值是在call()方法内
public class callable_test{
public static void main(String[] args){
//这里需要看下面的解释
ExecutorService ex = Executors.newCachedThreadPool();
ArrayList<Future<String>> list = new ArrayList<Future<String>>();
for (int i = 0; i < 10; i++) {
list.add(ex.submit(new callable_demo(i)));
}
for (Future<String> fs:list) {
try {
System.out.println(fs.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}finally {
ex.shutdown();
}
}
}
}
class callable_demo implements Callable<String>{
private int id;
public callable_demo(int id) {
this.id = id;
}
@Override
public String call() throws Exception {
String s = "hello word"+id;
TimeUnit.MILLISECONDS.sleep(100);
return s;
}
}
Executor 显示地创建Thread对象,简化并发编程
newCachedThreadPool 将为每一个任务都创建一个线程
FixedThreadPool 一次性预先执行代价高昂的线程分配,可以节省时间,限制线程数量
SingleThreadExecutor 只有1个线程,好处是不需要在共享资源上同步