If you do not want to change the decision to use Callable objects, you can also use queues and return the result from the threads in this way.
I rewrote your example as follows:
import java.util.PriorityQueue; import java.util.Queue; public class GetResultFromThread { public static void main(String[] args) throws Exception { Queue<String> queue = new PriorityQueue<String>(); int expectedResults = 2; for (int i = 0; i < expectedResults; i++) { new Example(queue).start(); } int receivedResults = 0; while (receivedResults < expectedResults) { if (!queue.isEmpty()) { System.out.println(queue.poll()); receivedResults++; } Thread.sleep(1000); } } } class Example extends Thread { private final Queue<String> results; public Example(Queue<String> results) { this.results = results; } @Override public void run() { results.add("result from thread"); } }
Please note that you should think about synchronization and concurrency!
Martin Jun 29 '10 at 16:17 2010-06-29 16:17
source share