Future is mostly usedTime-consuming thread computingThe main thread can query whether the future is finished and obtain the result after completing its own task. The callback function protected void done () is triggered when the task ends. Therefore, you only need to reload this function to implement some things at the end of the online process.
Futuretask is a runnablefuture <v>, which implements runnbale and futrue <v>. In addition, it can encapsulate runnable and callable <v>, it can be directly executed through thread packaging, or submitted to executeservice for execution. It can return the execution result through V get (). When the thread body is not completed, the main thread has been blocking and waiting, and the result is returned directly after execution.
Perform a simple test on the future packaging of runnable and callable. The get () method returns the result, and cancel (true) can forcibly terminate the thread.
Package COM. lzq. test; import Java. util. concurrent. callable; import Java. util. concurrent. executorservice; import Java. util. concurrent. executors; import Java. util. concurrent. future; public class testfuture {public static void main (string [] ARGs) {// create futuretask executorservice executor = executors through the thread pool. newfixedthreadpool (3); try {// testing package runnable future <?> Run = executor. submit (New runnable () {@ override public void run () {system. out. println ("runnable") ;}}); system. out. println ("runable:" + run. get (); // test the packaging callable future <string> call = executor. submit (New callable <string> () {@ override Public String call () throws exception {return "call" ;}}); // call the get method and the current thread will be blocked, it is suitable for time-consuming calculation system. out. println ("call:" + call. get (); // test cancel Fu Ture <string> cancelfuture = executor. submit (New callable <string> () {@ override Public String call () throws exception {try {While (true) {system. out. println ("cancel running. "); thread. sleep (50) ;}} catch (interruptedexception e) {system. out. println ("interrupted");} return "cancel false" ;}}); system. out. println ("cancel:" + cancelfuture. cancel (true); // test throwing an exception future <string> exception = exe Cutor. Submit (New callable <string> () {@ override Public String call () throws exception {Throw new exception ("new exception! ") ;}}); System. out. println ("exception:" + exception. get ();} catch (exception e) {system. out. println (E. tostring ();} // the thread that closes executor. shutdownnow ();}}
Use thread directly:
FutureTask<String> ft = new FutureTask<String>(new Callable<String>() { @Override public String call() throws Exception { return "call"; } }); Thread thread = new Thread(ft); thread.start();
To be continued.
Analysis of futuretask