java 如何在线程 run() 结束后立即调用方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3831889/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 03:34:59  来源:igfitidea点击:

how to call a method immediately after thread run() ends?

javaconcurrency

提问by Saravanan

I want to call a method that returns a string value. Actually this string value is an instance variable, and run()method put the value of the string.

我想调用一个返回字符串值的方法。实际上这个字符串值是一个实例变量,run()方法把字符串的值。

So, I want to call a method to get the string value updated by thread run()method..

所以,我想调用一个方法来获取线程run()方法更新的字符串值..

How can I do it...?

我该怎么做...?

回答by Tim Büthe

Check out Callablewhich is a Runnable that can return a result.

查看Callable,它是一个可以返回结果的 Runnable。

You use it like this:

你像这样使用它:

You write a Callable instead of a Runnable, for example:

你写一个 Callable 而不是 Runnable,例如:

public class MyCallable implements Callable<Integer> {
  public Integer call () {
    // do something that takes really long...
    return 1;
  }
}

You kick it of by submitting it to an ExecutionService:

您可以通过将其提交给 ExecutionService 来解决它:

ExecutorService es = Executors.newSingleThreadExecutor ();
Future<Integer> task = es.submit(new MyCallable());

You get back the FutureTaskhandle which will hold the result once the task is finished:

您将返回FutureTask句柄,该句柄将在任务完成后保存结果:

Integer result = task.get ();

FutureTask provides more methods, like cancel, isDoneand isCancelledto cancel the execution and ask for the status. The get method itself is blocking and waits for the task to finish. check out the javadoc for details.

FutureTask 提供了更多的方法,比如cancelisDoneisCancelled来取消执行并询问状态。get 方法本身正在阻塞并等待任务完成。查看 javadoc 了解详细信息。

回答by Steve Emmerson

class Whatever implements Runnable {
    private volatile String string;

    @Override
    public void run() {
        string = "whatever";
    }

    public String getString() {
        return string;
    }

    public void main(String[] args) throws InterruptedException {
        Whatever whatever = new Whatever();
        Thread thread = new Thread(whatever);
        thread.start();
        thread.join();
        String string = whatever.getString();
    }
}

回答by Mark Peters

Use a Callable<String>instead, submit it to an ExecutorService, and then call get()on the Future<String>it returns when you submit it.

使用 aCallable<String>代替,将其提交给 an ExecutorService,然后get()Future<String>提交时调用它返回。