Create a thread three: achieve Callable Interface

Create a thread through Callable and Future

  I. Create Callable interface implementation class, and implements call method, the method call as a thread of execution, and returns a value, may throw an exception.

  II. Create an instance of the implementation class Callable using FutureTask packaging Callable object, which object encapsulates FuturedTask call the return value of the method Callable object.

  iii. Use FutureTask object as a target Thread object, create and start a new thread.

  iv. FutureTask call the object's get methods to obtain the return value after the end of the sub-thread execution.

. 1  public  class TestCallable {
 2      public  static  void main (String [] args) {
 . 3          ThreadDemo TD = new new ThreadDemo ();
 . 4          // 1. Callable execution mode, it is necessary to achieve support FutureTask class, for receiving the operation result. 
. 5          a FutureTask, <Integer> = Result new new a FutureTask, <> (TD);
 . 6          new new the Thread (Result) .start ();
 . 7          // results after receiving thread 2. The operation 
. 8          the try {
 . 9              Integer Result = SUM .get () ;   // a FutureTask, it may be used to block 
10             System.out.println(sum);
11             System.out.println("------------------------------------");
12         } catch (InterruptedException | ExecutionException e) {
13             e.printStackTrace();
14         }
15     }
16 }
17 class ThreadDemo implements Callable<Integer>{
18     public Integer call() throws Exception {
19         int sum = 0;
20         for (int i = 0; i <= 100000; i++) {
 21              sum + = i;
22          }    
 23          return sum;
24      }    
 25 }
1   // Create a thread pool 
2 ExecutorService the pool = Executors.newFixedThreadPool (taskSize);
 . 3  // create multiple tasks that returns a value 
. 4 List <Future> List = new new the ArrayList <Future> (); 
 . 5  for ( int I = 0; I <taskSize; I ++ ) { 
 . 6      a Callable C = new new MyCallable (I + "" ); 
 . 7      // tasks and obtain Future object 
. 8      Future F = pool.submit (C); 
 . 9      List.add (F); 
 10  } 
 11  // Close thread pool 
12 is  the pool.shutdown (); 
 13 is  // get all the tasks run concurrently result 
14  for (Future F: List) { 
 15      // Get the return value from the task Future object, and outputs to the console 
16      System.out.println ( " RES: "+ f.get () toString ());. 
 . 17 } 

Guess you like

Origin www.cnblogs.com/HuiH/p/11910914.html