JAVA5 thread Pool

Source: Internet
Author: User

The role of the thread pool:

The thread pool function is to limit the number of threads executing in the system.
According to the environment of the system, can automatically or manually set the number of threads to achieve the best effect of the operation, less waste of system resources, many caused the system congestion efficiency is not high. The thread pool controls the number of threads, and other threads wait in line. A task completes, and the first task from the queue is executed. If there is no waiting process in the queue, this resource in the thread pool is waiting. When a new task needs to be run, it can start running if there is a waiting worker thread in the thread pool, otherwise enter the wait queue.

Why do I use a thread pool: reduces the number of times to create and destroy threads, each of which can be reused, and can perform multiple tasks to adjust the number of threads in the thread pool, depending on the system's affordability, and prevent the server from getting tired because of excessive memory consumption (each thread requires approximately 1MB of memory, The more threads open, the greater the memory consumed, and the last crash.

The difference between Threadgroup and Threadpoolexecutor

My own understanding is also always thought Threadgroup is threadpoolexecutor (thread pool), this is a very big misunderstanding, recently put the two carefully analyzed. A thread group represents a collection of threads. In addition, a thread group can contain other thread groups. The thread group forms a tree in which each thread group has a parent thread group in addition to the initial thread group. Allows a thread to access information about its own thread group, but does not allow it to access information about its thread group's parent thread group or any other thread group, and threads consume large amounts of resources, including memory and other system resources. In addition to the memory required by the thread object, each thread requires two potentially large execution call stacks. In addition, the JVM may create a native thread for each Java thread that consumes additional system resources. Finally, although the scheduling overhead of switching between threads is small, if there are many threads, environment switching can also seriously affect program performance. The thread pool is a waste of resources because of the generation of threads, so do not frequently manipulate threads is the place where you manage threads without it you can keep it dormant, which is that he manages threads for you and is much better than you manage. The thread pool provides a solution to the problem of threading lifecycle overhead and insufficient resources. By reusing threads for multiple tasks, the cost of thread creation is spread across multiple tasks. The benefit is that, because the thread already exists when the request arrives, it inadvertently eliminates the delay caused by the thread creation. This allows the request to be serviced immediately so that the application responds faster. Furthermore, by appropriately adjusting the number of threads in the thread pool, that is, when the number of requests exceeds a threshold, any other new requests are forced to wait until a thread is obtained to handle them, thereby preventing the lack of resources.

Executor Detailed:

The top-level interface in the Java thread pool is executor, but in the strictest sense executor is not a thread pool, but a tool for executing threads. The real thread pool interface is executorservice. Threadpoolexecutor is the underlying implementation of the Executors class. Let's introduce the next executors first.

Sun in Java5, Java thread of the class library to do a large number of extensions, where the thread pool is one of the new features of JAVA5, in addition to the thread pool, there are many multi-threaded-related content, for multithreaded programming has brought great convenience. In order to write efficient, stable and reliable multithreaded programs, the new contents of the thread section are particularly important.

The contents of the threading feature of Java5 line are all under Java.util.concurrent, which contains a large number of interfaces and classes, and familiarity with this part of the API is a difficult learning process. At present, there are few information and books on this aspect, and the books on the thread of the large-owned introduction are still in the knowledge level before Java5.

Of course, the new features do not have to do with the long thread program, the Java5 before the General Assembly can write very good multithreaded programs. It's just a different price.

The basic idea of thread pool is also the idea of an object pool, which opens up a memory space, in which many (not dead) threads are stored, and the pool thread execution schedule is handled by the pool manager. When a thread task is taken from a pool, the threads object is returned to the pool after completion, which avoids the performance overhead of repeatedly creating the thread object and saves the resources of the system.

Before Java5, to implement a thread pool is quite difficult, now Java5 for us to do everything, we just need to follow the API provided to use, you can enjoy the great convenience of the thread pool.

The JAVA5 thread pool is divided into several types: a fixed-size thread pool, a variable-size connection pool.

Before using the thread pool, you must know how to create a thread pool, in Java5, you need to know the Java.util.concurrent.Executors class API, which provides a number of static methods for creating connection pools that must be mastered.

Instance:

One, fixed size of the thread pool

Java Code    import java.util.concurrent.executors;   import  java.util.concurrent.executorservice;  /**  * java Threads: Thread pool-  *  *  @author  a   dministrator 2009-11-4 23:30:44  */   public class test {     Public static void main (String[] args)  {  //Creating a thread pool of reusable fixed threads    Executorservice pool = executors.newfixedthreadpool (2);  //Create implements the Runnable interface object, The Thread object of course also implements the Runnable interface    thread t1 = new mythread ();   thread t2  = new mythread ();   thread t3 = new mythread ();   Thread  t4 = new mythread ();   thread t5 = new mythread ();   //putting threads into pool for execution    pool.execute (t1);   pool.execute (T2);   Pool.execute (T3);   pool.execute (T4);   Pool.execute (T5);  //close thread pool    pool.shutdown (); nbsp; }  }   class mythread extends thread{   @Override  &   nbsp Public void run ()  {   System.out.println (Thread.CurrentThread (). GetName () + "executing ... ");  }  }     

The




Pool-1-thread-1 is executing ... &NBSP
Pool-1-thread-1 is executing ... &NBSP
Pool-1-thread-1 is executing ... &NBSP
Pool-1-thread-1 is executing ... &NBSP
Pool-1-thread-2 is executing ... &NBSP
Process finished with exit code 0&NBSP


Second, single task thread pool  

The code to create a pool object on the basis of the previous example is:  
//Creates a Executor that uses a single worker thread to run the thread in a unbounded queue. &NBSP
Java Code    executorservice pool = executors.newsinglethreadexecutor ();      


The output results are:


Pool-1-thread-1 is executing ...
Pool-1-thread-1 is executing ...
Pool-1-thread-1 is executing ...
Pool-1-thread-1 is executing ...
Pool-1-thread-1 is executing ...
Process finished with exit code 0


For both of these connection pools, the size is fixed, and when the thread (or task) of the pool to join exceeds the maximum size of the pool, the thread pool needs to be queued.

Once the threads in the pool have finished, a queued thread is run into the pool.

Three, the variable size of the thread pool

Similar to the above, just change the way the pool is created:

Create a thread pool that can create new threads as needed, but reuse them when previously constructed threads are available.
Java code Executorservice Pool = Executors.newcachedthreadpool ();


Pool-1-thread-5 is executing ...
Pool-1-thread-1 is executing ...
Pool-1-thread-4 is executing ...
Pool-1-thread-3 is executing ...
Pool-1-thread-2 is executing ...
Process finished with exit code 0


Four, delay connection pool

  Java code    import java.util.concurrent.executors;   import  java.util.concurrent.scheduledexecutorservice;   import java.util.concurrent.timeunit;   /**  * java Threads: Thread pool-  *  *  @author  administrator 2009-11-4 23:30:44&n   Bsp */   public class test {   Public static void main (String[)  args)  {  //Create a thread pool that can schedule commands to run or execute periodically after a given delay.    Scheduledexecutorservice pool = executors.newscheduledthreadpool (2);  // Creating a Runnable interface object, the Thread object of course also implements the Runnable interface    thread t1 = new mythread ();    Thread t2 = new mythread ();   Thread t3 = new mythread ( );   Thread t4 = new mythread ();   thread t5 = new  Mythread ();  //threadPut into the pool for execution   

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.