0
    public class Threadz implements Callable<String>{
    private boolean flag = false;

    @Override
    public String call() throws Exception {
        // TODO Auto-generated method stub
        for(int i = 0; i < 3; i++){
            Thread.sleep(2000);
        }
        flag = true;
        return "Done";
    }

    public boolean isDone(){
        return flag;
    }
}

    public class MyMain {
    public static void main(String[] args) {
        ExecutorService exe = Executors.newSingleThreadExecutor();
        Threadz threadz = new Threadz();
        Callable<String> cthread = threadz;
        Future<String> fut = exe.submit(cthread);

        while(true){
            try {
                if(!threadz.isDone())
                    System.out.println("Do something while waiting...");
                else{
                    System.out.println(fut.get());
                    System.out.print("Do something with the result...");
                    break;
                }
                Thread.sleep(1000);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

我使用上述代码的目标是生成一个将返回结果的线程,但在等待结果时不应暂停调用线程。这实际上有效,但我这样做正确吗?有没有正确的方法来做到这一点?而且,在返回结果后,可调用线程是否会自动死亡(释放资源和内存)?

谢谢。

4

1 回答 1

1
String callbackReturn = threadz.get();

如果需要,它会等待计算完成,然后检索其结果。

        ExecutorService exe = Executors.newSingleThreadExecutor();
        Threadz threadz = new Threadz();
        Callable<String> cthread = threadz;
        Future<String> fut = exe.submit(cthread);
        String callbackReturn = threadz.get();

当前线程将在此处等待。如果您不想暂停它,则处理它会导致其他线程。

于 2012-08-28T06:38:19.930 回答