multithreading via callable interface2016-05-26 12:35 460 People read comments (0) Collection report Category: J2SE (38)
Copyright NOTICE: This article is the original article of the blogger, without the permission of the blogger may not be reproduced.
Through the inheritance thread class to achieve multithreading, through the Runnable interface + static proxy to achieve multiple threads
One disadvantage, however, is that there is no return value when overriding the run method and cannot throw an exception
This problem can be solved by using the callable interface
Differences between the callable interface and the Runnable interface:
The 1.Callable method is call, and runnable is run
2.call method can throw an exception, but the Run method is not
3.Callable object can have return value after execution, run callable task can get a future object, through future object can understand task execution, can cancel task execution, and runnable cannot have return value
The implementation of multithreading has the following 4 steps:
1. Create a thread, create a callable implementation class race, and override the Call method
Executorservice Ser=executors.newfixedthreadpool (number of threads);
Race tortoise = new Race ();
2. Get Future Object
Future<integer> Result=ser.submit (Tortoise);
3. Get the return value
int Num=result.get ();
4. Stop Service
Ser.shutdown ();
Let's take the example of a turtle and rabbit race and go straight to the code.
[Java] View plain copy print? public class call { Public static void main (String[] args) throws InterruptedException, executionexception { executorservice ser=executors.newfixedthreadpool (2); Race tortoise=new race ("Tortoise", 1000); Race rabbit = new race ("Rabbit"); //Get value futUre<integer> resultr=ser.submit (rabbit); future<integer> resultt=ser.submit (Tortoise); thread.sleep (3000); rabbit.setflag (false); tortoise.setflag (false); int numr=resultr.get (); int numt=resultt.get (); system.out.println ("rabbit ---"+NUMR); system.out.println (" Tortoise ---"+numt);nbsp; //Stop Service ser.shutdown (); } } class race implements callable <Integer>{ private int step=0; private String name; private long time; private boolean flag=true;