When working with threads, one may encounter the need to retrieve values computed within the thread from the main method. This can present a challenge, as threads don't inherently have a mechanism for returning values. However, there are strategies to overcome this limitation.
One approach involves utilizing a customized thread class that includes a method to access the computed value:
<code class="java">public class Foo implements Runnable { private volatile int value; @Override public void run() { value = 2; // Compute the value in the thread } public int getValue() { return value; } }</code>
The main method can then utilize this custom thread as follows:
<code class="java">Foo foo = new Foo(); Thread thread = new Thread(foo); thread.start(); thread.join(); int value = foo.getValue(); // Retrieve the value computed in the thread</code>
By referencing the thread like an ordinary class, the main method gains access to the computed value.
The above is the detailed content of How can I retrieve values computed in a thread from the main method?. For more information, please follow other related articles on the PHP Chinese website!