Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2089318
  • 博文数量: 519
  • 博客积分: 10070
  • 博客等级: 上将
  • 技术积分: 3985
  • 用 户 组: 普通用户
  • 注册时间: 2006-05-29 14:05
个人简介

只问耕耘

文章分类

全部博文(519)

文章存档

2016年(1)

2013年(5)

2011年(46)

2010年(220)

2009年(51)

2008年(39)

2007年(141)

2006年(16)

我的朋友

分类: Java

2010-01-18 16:07:26

Producing return values from tasks
A Runnable is a separate task that performs work, but it doesn!ˉt return a value. If you want
the task to produce a value when it!ˉs done, you can implement theCallable interface rather
than the Runnable interface. Callable, introduced in Java SE5, is a generic with a type
parameter representing the return value from the method call( ) (instead of run( )), and
must be invoked using an ExecutorService submit( ) method. Here!ˉs a simple example:
//: concurrency/CallableDemo.java
import java.util.concurrent.*;
import java.util.*;
 
class TaskWithResult implements Callable {
  private int id;
  public TaskWithResult(int id) {
    this.id = id;
  }
  public String call() {
    return "result of TaskWithResult " + id;
  }
}
 
public class CallableDemo {
  public static void main(String[] args) {
    ExecutorService exec = Executors.newCachedThreadPool();
    ArrayList> results =
      new ArrayList>();
    for(int i = 0; i < 10; i++)
      results.add(exec.submit(new TaskWithResult(i)));
    for(Future fs : results)
      try {
        // get() blocks until completion:
        System.out.println(fs.get());
      } catch(InterruptedException e) {
        System.out.println(e);
        return;
      } catch(ExecutionException e) {
        System.out.println(e);
      } finally {
        exec.shutdown();
      }
  }
} /* Output:
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
*///:~
The submit( ) method produces a Future object, parameterized for the particular type of
result returned by the Callable. You can query the Future with isDone( ) to see if it has
completed. When the task is completed and has a result, you can call get( ) to fetch the
result. You can simply call get( ) without checking isDone( ), in which case get( ) will block
until the result is ready. You can also call get( ) with a timeout, or isDone( ) to see if the
task has completed, before trying to call get( ) to fetch the result. 
The overloaded Executors.callable( ) method takes a Runnable and produces a
Callable. ExecutorService has some "invoke" methods that run collections of Callable
objects. 
 
copied from Thinking in java
阅读(479) | 评论(0) | 转发(0) |
0

上一篇:Using Executors

下一篇:Joining a thread

给主人留下些什么吧!~~