java-thread Pool topic (American group face test) __java

Source: Internet
Author: User
Tags stub
java-thread Pool topic (American group face test)

To the American group interview, asked what is the thread pool, how to use, why use, the following to make a summary

1, what is the thread pool: Java.util.concurrent.Executors provides an implementation of a Java.util.concurrent.Executor interface to create a thread pool

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.
Suppose a server completes a task by the time it takes to create the thread time, T2 the time of the task in the thread, T3 destroy the thread time. T1

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): for creating and managing 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, Task Interfaces (tasks): an interface that each task must implement for the execution of a work-thread scheduling task, which mainly prescribes the entry of the task, the finishing of the task after execution, and the execution status of the task;
                 4, Task queue (Taskqueue): For storing tasks that are not processed. Provides a buffer mechanism.

Thread pooling technology is focused on how to shorten or adjust the t1,t3 time technology, thereby improving 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.

2. The common thread pool ①newsinglethreadexecutor a thread pool of individual threads, that is, a thread pool in which only one thread works at a time, and a single thread serial execution task ②newfixedthreadexecutor (n) a fixed number of thread pools. A task that is not committed is a thread until the maximum number of thread pools is reached, and then the wait queue is entered until the previous task completes before continuing with the ③newcachethreadexecutor (recommended) cache thread pool, when the thread pool size exceeds the threads required to process the task. A thread that is partially idle (typically 60 seconds without execution) is reclaimed, and when a task comes in, it is smart to add a new thread to execute. ④newschedulethreadexecutor a thread pool of unlimited size that supports timed and periodic execution threads

Java provides a more powerful thread pool, I believe that understanding the workings of the thread pool, see the Class library thread pool will not feel unfamiliar.

Article 2:

introduction to Java thread pool usage description

The use of threads occupies a very important place in Java, and the use of thread pools is extremely rudimentary in the JDK version of jdk1.4. The situation has changed a lot since the jdk1.5. Jdk1.5 added the Java.util.concurrent package, which mainly describes the use of the Java thread and thread pool. Provides a great deal of help for our threading problems in development. Two: Thread pool

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:

1. The number of times to create and destroy threads is reduced, and each worker thread can be reused to perform multiple tasks.

2. According to the system's affordability, adjust the number of threads in the thread pool, to prevent the use of excessive memory, and the server tired down (each thread needs about 1MB of memory, the more threads open, the consumption of memory will be larger, the last crash).

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.

Some of the more important classes:

Executorservice

The true thread pool interface.

Scheduledexecutorservice

can be similar to Timer/timertask to solve problems that require repetitive tasks.

Threadpoolexecutor

The default implementation of the Executorservice.

Scheduledthreadpoolexecutor

Inherit Threadpoolexecutor Scheduledexecutorservice interface implementation, periodic task scheduling class implementation.

It is more complicated to configure a thread pool, especially if the thread pool is not clearly understood, it is likely that the configured thread pool is not superior, so there are some static factories in the executors class that generate some common thread pools.

1. Newsinglethreadexecutor

Create a single-threaded thread pool. This thread pool has only one threads working, which is equivalent to single-threaded serial execution of all tasks. If this unique thread ends because of an exception, then there is a new thread to replace it. This thread pool guarantees that the order in which all tasks are performed is performed in the order in which they are submitted.

2.newFixedThreadPool

Create a fixed size thread pool. Create a thread each time a task is committed, until the thread reaches the maximum size of the thread pool. The size of the thread pool will remain unchanged once it reaches its maximum value, and if a thread ends up executing an exception, the thread pool complements a new thread.

3. Newcachedthreadpool

Create a cacheable pool of threads. If the thread pool is larger than the threads needed to process the task,

A thread that is partially idle (60 seconds without a task) is reclaimed, and when the number of tasks increases, the thread pool can intelligently add new threads to handle the task. This thread pool does not limit the thread pool size, and the thread pool size is entirely dependent on the maximum threading size that the operating system (or JVM) can create.

4.newScheduledThreadPool

Create a thread pool of infinite size. This thread pool supports the need for timing and periodic execution of tasks.

Instance

1:newsinglethreadexecutor

Package com.thread;
 * * * through the implementation of the Runnable interface, implementation
 of multithreading * Runnable class is run () method;
 * But no start method
 * Reference:
 * 
http:// blog.csdn.net/qq_31753145/article/details/50899119

 * */Public

class Mythread extends Thread { 

    @Override Public
    void Run () {
        //TODO auto-generated Method Stub
//        Super.run ();
    System.out.println (Thread.CurrentThread (). GetName () + "executing ...");
    } 
Package com.thread;
Import Java.util.concurrent.ExecutorService;

Import java.util.concurrent.Executors; * * * Through the implementation of the Runnable interface, implementation of multithreading * Runnable class is run () method; * But no Start method * Reference: * Http://blog.csdn.net/qq_31753145/article/deta  ils/50899119 * */public class singlethreadexecutortest{public static void Main (string[] args) {// TODO auto-generated Method Stub//create a thread pool executorservice that can reuse the number of fixed threads pool=executors.newsinglethreadexecut
        
        or ();
        
        
        Creating the Runnable interface object, thread object also realizes the Runnable interface;
        
        Thread t1=new mythread ();
        
        Thread t2=new mythread ();
        
        Thread t3=new mythread ();
        
        Thread t4=new mythread ();
        
        Thread t5=new mythread ();

        Put the thread into the pool to execute; pool.execute (t1);

        Pool.execute (T2);

        Pool.execute (T3);

        Pool.execute (T4);
        
        Pool.execute (T5);
    Close the thread pool Pool.shutdown ();    
     

    }

} 

Results:

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 ....

2newFixedThreadPool

Package com.thread;
Import Java.util.concurrent.ExecutorService;

Import java.util.concurrent.Executors; * * * Through the implementation of the Runnable interface, implementation of multithreading * Runnable class is run () method; * But no Start method * Reference: * Http://blog.csdn.net/qq_31753145/article/deta ils/50899119 * */public class fixedthreadexecutortest{public static void Main (string[] args) {// 
        
        TODO auto-generated Method Stub//create a thread pool Executorservice pool=executors.newfixedthreadpool (2) with a reusable number of fixed threads;
        
        
        Creating the Runnable interface object, thread object also realizes the Runnable interface;
        
        Thread t1=new mythread ();
        
        Thread t2=new mythread ();
        
        Thread t3=new mythread ();
        
        Thread t4=new mythread ();
        
        Thread t5=new mythread ();

        Put the thread into the pool to execute; pool.execute (t1);

        Pool.execute (T2);

        Pool.execute (T3);

        Pool.execute (T4);
        
        Pool.execute (T5);
        
Close the thread pool Pool.shutdown ();     

    }

} 

Results:

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-2 is executing ....

3, Newcachedthreadpool

Package com.thread;

Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
 * * * through the implementation of the Runnable interface, implementation
 of multithreading * Runnable class is run () method;
 * But no start method
 * Reference:
 * 
http:// blog.csdn.net/qq_31753145/article/details/50899119

 * * */Public

class cachedthreadexecutortest{
     

    public static void Main (string[] args) {
        

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.