如何在处理THREAD之前对我的方法执行RETURN?

时间:2013-04-14 07:33:46

标签: multithreading methods return

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

感谢。

1 个答案:

答案 0 :(得分: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);
}