1. The Task inheritance Callable, Runable
import java.util.concurrent.Callable; import java.util.function.Consumer; public class CallbackableFeatureTask<V> implements Callable<V>, Runnable { private Callable<V> mainProcess; private Consumer<V> callbackFunction; @Override public V call() throws Exception { V result = mainProcess.call(); callbackFunction.accept(result); return result; } public CallbackableFeatureTask(Callable<V> callable, Consumer<V> callbackFunction) { this.mainProcess = callable; this.callbackFunction = callbackFunction; } @Override public void run() { try { call(); } catch (Exception ex) { } } }
2. Test the code
public class CallbackableFeatureTaskTest { private static ExecutorService executorService = Executors.newFixedThreadPool(5); public static void main(String[] args) { CallbackableFeatureTask<String> task = new CallbackableFeatureTask<>(new Callable<String>() { @Override public String call() throws Exception { return "Hello China!"; } }, (String v) -> { System.out.println(v); }); //1. Support for direct use threads the Runnable new new the Thread (Task) .start (); // 2. Support thread pooling a Callable Future <String> ExecutorService.submit Result = ((a Callable <String> ) Task); the try { the System .out.println ( "return result using a thread pool is:" + result.get ()); } the catch (Exception EX) { }
executorService.shutdown();
}
}
The results are as follows:
! The Hello China
! The Hello China
using a thread pool The result is: Hello China!
Here are just doing a teaching Demo
Late points can be optimized: realized Future <V> interface inherit the like FutureTask