1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | class Executor { public <T> void execute(Callable<T> task, BiConsumer<T, ? super Exception> callback) { CallableThread<T> thread = new CallableThread<>(task, callback); thread.start(); } class CallableThread<T> extends Thread { Callable<T> task; BiConsumer<T, ? super Exception> callback; public CallableThread(Callable<T> task, BiConsumer<T, ? super Exception> callback) { this.task = task; this.callback = callback; } public void run() { System.out.println("running task on thread : " + Thread.currentThread().getName()); try { T t = task.call(); callback.accept(t, null); } catch (Exception ex) { callback.accept(null, ex); } } } } |
Caller:
1 2 3 4 5 6 7 8 | System.out.println("running task on thread : " + Thread.currentThread().getName()); new Executor().execute(() -> "HELLO WORKD", (result, ex) -> { System.out.println("result: " + result); System.out.println("exception: " + ex); }); System.out.println("finished running task on thread : " + Thread.currentThread().getName()); |
Output:
1 2 3 4 5 | running task on thread : main finished running task on thread : main running task on thread : Thread-0 result: HELLO WORKD exception: null |
It appears that, the Executor is submitting the Callable to execution and on complete it invokes the callback functional interface.
No comments:
Post a Comment