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

【Thinking in Java】Java Callable的使用

2015-05-07 22:23 120 查看
  Callable<>和Runable类似,都是用于Java的并发执行。

  唯一的区别是,Runable的run方法的返回是void,而Callable的call方法是有返回值的。

  call方法返回的类型是实现Callable<?>泛型接口时所指定的类型,不然会编译出错。

  那么,怎样获取call方法的返回值呢?——通过执行Callable,可以返回的Future对象,通过调用future对象的get方法来获取call方法的返回值。

  综上,你把Callable当成是有返回值的Runable就行了,只不过Callable的是call,Runable的是run。

  下面是演示代码:

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

public class CallableTest{
public static void main(String[] args) {
ExecutorService executorService=    //创建线程池
Executors.newCachedThreadPool();
ArrayList<Future<String>> list=
new ArrayList<Future<String>>();
for (int i = 0; i < 10; i++) {
list.add(executorService    //通过submit方法来提交Callable到线程池中执行
.submit(new TaskWithResult()));
}
for (Future<String> future : list) {
try {
System.out.println(future.get()); //通过get方法来获取call返回值
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}

static class TaskWithResult implements Callable<String>{
private static int taskNum=0;
private int taskId=taskNum;
public TaskWithResult() {
taskNum++;
}

@Override
public String call() throws Exception {
try {
Thread.sleep(this.taskId*1000);    //我制造的时间差,更直观地显示call和run方法的相似性。
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Result of TaskWithResult: "+this.taskId;
}

}

}


  运行结果:

  Result of TaskWithResult: 0
  Result of TaskWithResult: 1
  Result of TaskWithResult: 2
  Result of TaskWithResult: 3
  Result of TaskWithResult: 4
  Result of TaskWithResult: 5
  Result of TaskWithResult: 6
  Result of TaskWithResult: 7
  Result of TaskWithResult: 8
  Result of TaskWithResult: 9

  以上的运行结果是每隔一秒打印一行的,这说明,call和run是差不多的。

  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: