0

我的类中有一个方法返回在线程上处理的 STRING,我需要等待解决线程上的工作,直到执行 RETURN。有什么办法解决吗??我可以举一个简单的例子吗?

谢谢。

4

1 回答 1

0

如果 java 那么 Callable 接口正是为此完成的:

 class CalculateSomeString implements Callable<String>{
     @Override
     public String call() throws Exception {
         //Simulate some work that it takes to calculate the String
         Thread.sleep(1000);
         return "CoolString";
     }
 }

以及运行它的代码

public static void main(String[] args) throws InterruptedException, ExecutionException {
    ExecutorService service = Executors.newFixedThreadPool(1);
    Future<String> future = service.submit(new CalculateSomeString());
    //this will block until the String has been computed
    String result = future.get();
    service.shutdown();
    System.out.println(result);
}
于 2013-04-14T07:43:49.437 回答