Use the thread pool implementation, asynchronous computation thread

Thread class, to perform tasks:

package com.yonyou.sci.gateway.exec;

import java.util.concurrent.Callable;

public class CallableTask<I extends Number> implements Callable<Integer> {

    private Integer num;

    public CallableTask () {}

    // use the received configuration parameters embodiment 
    public CallableTask (Integer NUM) {
         the this .num = NUM;
    }

    @Override
    public Integer call () {
        COUNT Integer = 0 ;
          for ( int I =. 1; I <= NUM; I ++ ) {
              // The parameters passed iteratively adding 
             COUNT = COUNT + I;
         }
        return count;
    }

}

To perform the above tasks using a thread pool mode:

package com.yonyou.sci.gateway.exec;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * Use a thread pool to achieve parallel computing
 * / 
Public  class TaskMain {
     public  static  void main (String [] args) throws Exception {
         // create a fixed length of thread pool 
        ExecutorService Executors.newFixedThreadPool ES = (2 );

        // use the thread pool mode, a thread of execution subclass 
        Future <Integer> R1 = es.submit ( new new CallableTask <Integer> (100 ));
        Future<Integer> r2 = es.submit(new CallableTask<Integer>(200));

        // get the result of the calculation and print out 
        System.out.println (r1.get ());
        System.out.println(r2.get());

        // close the thread pool 
        es.shutdown ();

    }

}

 

Guess you like

Origin www.cnblogs.com/tangshengwei/p/11723523.html