Java parallel asynchronous programming, thread pool +futuretask+callable+executorservice__thinking

Source: Internet
Author: User
Tags thread class

Java introduces a new concurrency package in JDK1.5 java.util.concurrent the package is written specifically for Java processing concurrency.

The familiar use of multithreading in Java is in two different ways. Continue the thread class to implement Runnale. Two ways are simple and convenient.

After Jdk1.5, there is a third way to implement the method, using the callable interface Furutetask class and Executorservice interface in the contract.

Let's talk about the new implementation before we discuss the traditional Java execution process

First, a simple program to generate random numbers, in the implementation of the method of generating random numbers, sleep 1s simulation method calls time consuming, put the results into the collection, and finally calculate the total results.

public class count{public static void Main (string[] args) throws Interruptedexception {long start = System.
           Currenttimemillis ();
           Count count = new count ();
           list<integer> res = new arraylist<> ();
           Res.add (Count.random ());
           Res.add (Count.random ());
           Res.add (Count.random ());
           Res.add (Count.random ());
           int totle = 0;
           for (int i = 0; i < res.size (); i++) {totle+=res.get (i);
           Long end = System.currenttimemillis ();
           SYSTEM.OUT.PRINTLN ("Operation End time Consuming:" + (End-start) + "Ms Totle:" +totle); System.out.println ("Exits the main thread.)
         ");
    int random () throws interruptedexception{Thread.Sleep (1000);//return new Random (). Nextint (100); }
  }

The results are as follows

Operation End time consuming: 4000ms  totle:66
exit main thread.

In traditional writing, a single-threaded operation, serial operation, when the method Count.random () is invoked, the main thread is blocked until the sleep time arrives, and the main thread is awakened automatically.

So is there any way to reduce the blocking time of main main thread? Can you let these operations run in parallel? What is the benefit of running in parallel?

The benefits of parallelism can reduce the number of method execution times, such as the random () method for parallel computations, which means that main thread blocking is only 1s, blocking time is reduced by 75%

Java provides us with multithreading mechanism, using multithreading we can achieve the parallel operation of the method, the implementation of multithreading, implementation of the Runnable interface again run, inheritance thread rewrite run; Because the Run method does not return a value, We manually create a large number of threads and maintain threads is a very annoying thing, and create a thread is very resource-intensive operation, can have a pool to help us manage the thread. Is there a class that transparently makes transparent concurrent asynchronous operations? This is not before the JDK1.5, after the 1,5 appeared a new package, specifically for concurrent development of the package, the use of the class and interface provided in the contract, will be easily implemented. Concurrent programming.

Import java.util.ArrayList;
Import java.util.List;
Import Java.util.Random;
Import java.util.concurrent.Callable;
Import java.util.concurrent.ExecutionException;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;

 Import Java.util.concurrent.FutureTask;   public class Testmain {public static void main (string[] args) throws Interruptedexception, executionexception {new
  Testmain (). exec (); } void Exec () throws Interruptedexception, executionexception{//Asynchronous Task List list<futuretask<integer>>
    Futuretasks = new arraylist<futuretask<integer>> ();
    The thread pool initializes 10 threads and the JDBC connection pool is a meaning implementation reuse executorservice Executorservice = Executors.newfixedthreadpool (10);
    Long start = System.currenttimemillis (); A similar implementation of the Run method callable is an interface in which handwritten logical code callable<integer> callable = new callable<integer> () {@Ove Rride public Integer Call () throws Exception {integer res = new Random (). Nextint (100);
        Thread.Sleep (1000);
        SYSTEM.OUT.PRINTLN ("Task execution: Get to the result:" +res);
      return res;
    
    }
    }; for (int i=0;i<10;i++) {///Create an asynchronous task futuretask<integer> Futuretask = new Futuretask<integer> (call
      ABLE);
      Futuretasks.add (Futuretask);
             Commit asynchronous tasks to the thread pool, so that the thread pool management task is super cool. 
    Because it is an asynchronous parallel task, this does not block Executorservice.submit (Futuretask);
       int count = 0; for (futuretask<integer> futuretask:futuretasks) {//futuretask.get () Gets the result we want//the method has an overloaded get (l
  Ong Timeout, timeunit unit) The first parameter is the maximum wait time, the second is the units of the time count+= futuretask.get ();
     Long end = System.currenttimemillis ();
     SYSTEM.OUT.PRINTLN (the task of the thread pool is complete: The result is: "+count+", main thread off, thread cleanup);
     SYSTEM.OUT.PRINTLN ("Use Time:" + (End-start) + "MS");
    
  Clean thread pool Executorservice.shutdown (); }
}

If the above situation does not need asynchronous parallelism, the program will sleep at least 10s

The results after use

Task execution: Getting to results:
job execution: Getting to results: The
task execution: Getting to the results: task execution: Getting to results: The task execution: Getting to the results: the
task execution: Getting to the results: 8
Task execution: Getting to the results: the
task execution: Getting to the results: 3
Task execution: Getting to results:
the task execution: getting to the result:
the task of the thread pool is complete: The result is: 621,main thread shutdown, thread cleanup

We're trying to reduce the size of the thread pool by half.

Task execution: Getting to results: task
execution: Getting to results:
task execution: Getting to Results: Task execution: Getting to Results: 8 task execution: Getting to results:
86
task execution: Getting to results:
task execution: Getting to results: 4
Task execution: Getting to results: A
task execution: Get to Result:
the task of the thread pool is complete: The result is: 367,main thread shutdown, To clean up the thread

Use time: 2017ms

Ext: http://liuyieyer.iteye.com/blog/2083111

Attachment: Principle of thread pool engineering

  Multithreading technology mainly solves the problem of multiple threads executing in the processor unit, which can significantly reduce the idle time of the processor unit and increase the throughput capacity of the processor unit.          assume that a server completes a task by T1 the time it takes to create a thread, T2 the time it takes to perform a task in the thread, T3 destroy the thread time.     if: T1 + T3 is much larger than T2, you can use a thread pool to improve server performance.                 A thread pool consists of the following four basic components:                 1, Thread pool Manager (ThreadPool): Used to create and manage thread pools, including creating thread pools, destroying thread pools, adding new tasks;                  2, Work thread (Poolworker): Thread pool threads, in the absence of tasks in the waiting state, you can cycle the execution of tasks;                  3, Mission Interface (Task): an interface that each task must implement for the execution of a work-thread scheduling task, which primarily sets the portal for the task , the finishing work after the task is finished, the execution status of the task, etc.                  4, Task queue (Taskqueue): For storing tasks that are not processed. Provides a buffer mechanism.                &nBsp     thread pooling technology is focused on how to shorten or adjust the t1,t3 time technology, so as to improve server program performance. It arranges t1,t3 at the start and end of a server program, or some idle time, so that there is no t1,t3 overhead when a server program processes a client request. The     thread pool not only adjusts the time period generated by T1,T3, but it also significantly reduces the number of threads created, looking at an example:     Suppose a server handles 50,000 requests a day, And each request requires a separate thread to complete. In the thread pool, the number of threads is generally fixed, so the total number of threads generated will not exceed the number of thread pool threads, and the total number of threads is 50000 if the server does not use the thread pool to process these requests. The general thread pool size is far less than 50000. Therefore, server programs that utilize thread pools do not waste time processing requests in order to create 50000, thereby increasing efficiency.

The

    code implementation does not implement the task interface, but instead joins the Runnable object to the thread pool manager (ThreadPool), and the rest is done by the thread pool Manager (ThreadPool)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.