1, requirements: Through the thread pool thread object, using the callable interface to complete the two number sum operation.
2, the Code implementation:
(1) Callable Interface implementation class
1 Importjava.util.concurrent.Callable;2 3 Public classMycallableImplementsCallable<integer> {4 //member Variables5 intx = 5;6 inty = 3;7 8 //Construction Method9 Publicmycallable () {Ten } One A PublicMycallable (intXinty) { - This. x =x; - This. y =y; the } - - @Override - PublicInteger Call ()throwsException { + returnX +y; - } +}
(2) Test class
1 Importjava.util.concurrent.ExecutionException;2 ImportJava.util.concurrent.ExecutorService;3 Importjava.util.concurrent.Executors;4 Importjava.util.concurrent.Future;5 6 Public classThreadPoolDemo {7 Public Static voidMain (string[] args)throwsInterruptedexception,8 executionexception {9 //To create a thread pool objectTenExecutorservice ThreadPool = Executors.newfixedthreadpool (2); One A //Create a callable interface subclass object - //mycallable C = new mycallable (); -Mycallable C =NewMycallable (100, 200); themycallable C2 =NewMycallable (10, 20); - - //gets the thread in the thread pool, calls the call () method in the callable interface subclass object, and completes the sum operation - //<Integer> future<integer> Submit (callable<integer> Task) + //Future Result Object -future<integer> result =Threadpool.submit (c); + //The result type returned by the Get method for this future AInteger sum =result.get (); atSystem.out.println ("sum=" +sum); - - //Re-demo -result =threadpool.submit (C2); -sum =result.get (); -System.out.println ("sum=" +sum); in //Close thread pool (can not be closed) - to } +}
3. Operation Result:
l Callable Interface implementation class
02027_ thread Pool Exercise: Returns the result of a two number addition