package tag7_threads; import java.util.concurrent.Callable; class Future implements Runnable { private T value = null; private Exception exc = null; private Callable work; private Thread task; public Future(Callable w) { work = w; task = new Thread(this); task.start(); } public void run() { try { value = work.call(); } catch (Exception e) { exc = e; } } public T get() throws Exception { task.join(); if (exc != null) { throw exc; } return value; } } public class FutureTest { public static void main(String[] args) { Future f; f = new Future<>(() -> { int x = 0; x /= 0; for (long i = 0; i < 10000000000L; i++) { x += i; } return x; }); System.out.println("Wird im Hintergrund berechnet..."); System.out.println("tue irgendwas anderes..."); for (int i = 0; i < 10; i++) { System.out.println(i); } System.out.println("will darauf zugreifen:"); try { Thread.sleep(3000); } catch (InterruptedException e) {} try { System.out.println(f.get()); } catch (Exception e) { e.printStackTrace(); } } }