Getting the output of a Thread

后端 未结 7 1524
时光说笑
时光说笑 2021-02-02 01:28

What do you think is the best way for obtaining the results of the work of a thread? Imagine a Thread which does some calculations, how do you warn the main program the calculat

7条回答
  •  天涯浪人
    2021-02-02 01:38

    Don't use low-level constructs such as threads, unless you absolutely need the power and flexibility.

    You can use a ExecutorService such as the ThreadPoolExecutor to submit() Callables. This will return a Future object.

    Using that Future object you can easily check if it's done and get the result (including a blocking get() if it's not yet done).

    Those constructs will greatly simplify the most common threaded operations.

    I'd like to clarify about the blocking get():

    The idea is that you want to run some tasks (the Callables) that do some work (calculation, resource access, ...) where you don't need the result right now. You can just depend on the Executor to run your code whenever it wants (if it's a ThreadPoolExecutor then it will run whenever a free Thread is available). Then at some point in time you probably need the result of the calculation to continue. At this point you're supposed to call get(). If the task already ran at that point, then get() will just return the value immediately. If the task didn't complete, then the get() call will wait until the task is completed. This is usually desired since you can't continue without the tasks result anyway.

    When you don't need the value to continue, but would like to know about it if it's already available (possibly to show something in the UI), then you can easily call isDone() and only call get() if that returns true).

提交回复
热议问题