In concurrent programming, runnable is generally used, and then thrown to the thread pool to finish, in which case the result of the thread is not required.
So the return value of Run is the void type.
If it is a multi-threaded collaboration program, such as the Philippine-la-1,1,2,3,5,8 series, ... Use multithreading to calculate.
But the latter need the former result, it needs to use the callable interface.
Callable usage is just like runnable, except that the call method is called, and the method has a generic return value type that you can specify arbitrarily.
Threads are part of the asynchronous computing model, so you can't get function return values directly from other threads.
That's when the future comes out. Futrue can monitor when the target thread calls call, and when you invoke the Get () method of the future to get the result, the current thread begins to block, and the call method ends the return result.
The following three simple pieces of code can be very concise to reveal this meaning:
The Runnable interface implements concurrent programming with no return value.
The callable implements concurrent programming of the presence return value. (Call's return value string is affected by generics)
Also callable, use the future to get the return value.
Paste a complete and running program code Futuretest.java
Packagedemo.future;Importjava.util.ArrayList;Importjava.util.List;Importjava.util.concurrent.*; /*** Experiment with Java's future usage*/ Public classFuturetest { Public Static classTaskImplementsCallable<string>{@Override PublicString Call ()throwsException {String tid=string.valueof (Thread.CurrentThread (). GetId ()); System.out.printf ("Thread#%s:in call\n", Tid); returnTid; } } Public Static voidMain (string[] args)throwsinterruptedexception, executionexception {List<Future<String>> results =NewArraylist<future<string>>(); Executorservice es=Executors.newcachedthreadpool (); for(inti=0; i<100;i++) Results.add (Es.submit (NewTask ())); for(future<string>res:results) System.out.println (Res.get ()); } }
Java future usage and meaning a sentence break [turn]