public class ReturnValueWithThread { public static void main(String[] args) { MyThread t = new MyThread(); t.start(); // busy doing something..... while (!t.isDone()) { Thread.yield(); } System.out.println(t.getMessage()); } static class MyThread extends Thread { private boolean done; private String message; /** * {@inheritDoc} */ @Override public void run() { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } done = true; message = "Hello World"; } public boolean isDone() { return done; } public String getMessage() { return message; } } }
In Java 5 onwards, this task can be easily achieved by using java.util.concurrent.ExecutorService and java.util.concurrent.Future.
import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class ReturnValueWithExecutor { public static void main(String[] args) { ExecutorService e = Executors.newFixedThreadPool(1); Future<String> f = e.submit(new Callable<String>() { @Override public String call() throws Exception { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } return "Hello World"; } }); // busy doing something... try { String message = f.get(); System.out.println(message); } catch (InterruptedException e1) { e1.printStackTrace(); } catch (ExecutionException e1) { e1.printStackTrace(); } } }
No comments:
Post a Comment