The recent project used a feature that needed to implement multi-threaded distribution tasks and required the return value of the task, which had been implemented runnable interface, but the Run method was to return void. Later on the Internet to check the next JAVA1.5 began to have a callable.
Here's a look at how to daoteng this thing.
Importjava.util.concurrent.Callable;/*** @ class description Thread Business processing *@authorDaventsang * @date 2016-11-16 **/ Public classPooltaskImplementsCallable<string> { PrivateString ID; @Override PublicString Call ()throwsException {return"Current thread Name:" + Thread.CurrentThread (). GetName () + ":" +ID; } PublicString getId () {returnID; } Public voidsetId (String id) { This. ID =ID; }}View Code
First, create a class to implement the callable interface. Here is a description of the JDK API for the callable interface:
Callable<v>
A task that returns the result and may throw an exception. The implementing person defines a method called call without any parameters .
The callable interface is Runnable similar in that both are designed for classes whose instances might be executed by another thread. However, Runnable does not return a result and cannot throw a checked exception.
Executorsclass contains some practical methods for converting from other ordinary forms to callable classes.
V is the object that needs to be returned.
To execute this implementation class, we need to create a thread pool
Importjava.util.ArrayList;Importjava.util.List;ImportJava.util.concurrent.CompletionService;Importjava.util.concurrent.ExecutionException;ImportJava.util.concurrent.ExecutorCompletionService;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;Importjava.util.concurrent.Future; Public classPoolutils {//Scalable thread Pool Private StaticExecutorservice Cachedpool =Executors.newcachedthreadpool (); Public StaticCompletionservice<string> Completionservice =NewExecutorcompletionservice<string>(Cachedpool); Privatepooltask task; PublicString AddTask ()throwsinterruptedexception, executionexception{//Add a taskfuture<string> future =Completionservice.submit (Task); //Check to see if a second thread comes inThread.Sleep (1000); List<Future<String>> list =NewArraylist<future<string>>(); System.out.println (Completionservice.take (). get ()); List.add (future); returnCompletionservice.take (). get (); } PublicPooltask Gettask () {returntask; } Public voidsettask (pooltask Task) { This. Task =task; } }View Code
Thread.Sleep (); Call this method because the previous add task is called with an array of threads, look at Executors.newcachedthreadpool (); Can you create threads on your own as needed?
Let's look at the source code of the Submit () method,
Public future<v> Submit (callable<v> Task) { if (task = = null) throw new NullPointerException (); runnablefuture<v> f = newtaskfor (Task); Executor.execute (new Queueingfuture (f)); return f; }
Private class Queueingfuture extends Futuretask<void> { queueingfuture (runnablefuture<v> Task) { Super (task, NULL); This.task = task; } protected void Done () {Completionqueue.add (Task);} Private final future<v> task; }
Chase the source will find that there is a queue exists. Submit add a task will be placed in the queue. So we don't have to show up to create a queue.
Call class:
Importjava.util.concurrent.ExecutionException; Public classTest { Public Static voidMain (string[] args)throwsinterruptedexception, executionexception {thread[] Thread=NewThread[10]; for(inti = 0;i<thread.length;i++) {Thread[i]=NewThread (NewA ()); } for(Thread th:thread) {Th.start (); } }}classAImplementsrunnable{@Override Public voidrun () {Pooltask task=NewPooltask (); Task.setid ("Daven"); Poolutils Utils=Newpoolutils (); Utils.settask (Task); Try{String a=Utils.addtask (); } Catch(Interruptedexception |executionexception e) {E.printstacktrace (); } }}View Code
Invoking a class with multiple threads to invoke is due to simulating the scenario of the project.
These are some records for your own recollection. Encounter problems first find out the reason, then go online to find and then find the API Chase source.
Callable implementing Java Multithreading