How about this solution?
It does not use the Thread class, but it is parallel, and thus it does exactly what you request
ExecutorService pool = Executors.newFixedThreadPool(2); // creates a pool of threads for the Future to draw from Future<Integer> value = pool.submit(new Callable<Integer>() { @Override public Integer call() {return 2;} });
Now all you do is say value.get() whenever you need to capture the return value, the thread starts just a second when you give the value value, so you never need to say threadName.start() .
What is Future , this is a promise to the program, you promise the program that you will receive its value, which they will need in the near future
If you call .get() on it before it finishes, the thread calling it will just wait until it is executed
Electric Coffee Dec 28 '13 at 9:11 2013-12-28 21:11
source share