Java thread pool Detailed (instance)

Source: Internet
Author: User

In the previous article, we created a thread when we used the thread, so it was easy to implement, but there was a problem:

If you have a large number of concurrent threads, and each thread is finished with a short task, creating a thread frequently can greatly reduce the efficiency of the system because it takes time to create threads and destroy threads frequently.

So is there a way to make threads reusable, to perform one task, not to be destroyed, and to continue to perform other tasks.

In Java, this can be achieved by thread pooling.

What does the 1 thread pool do?

There are usually two forms of network requests:

First, the request is not very frequent, and after each connection will be maintained for a considerable period of time to read data or write data, the last disconnect, such as file downloads, network streaming media.

Another form is a frequent request, but a small amount of data is disconnected after the connection is read/written. Considering the concurrency problem of the service, if each request comes in and the service starts a thread for it, the resource for the service can be a huge waste, especially in the second case.

Because, in general, creating a thread takes a certain amount of time, which is T1, and the time to read/write the service is T2, when t1>>t2, we should consider a strategy or mechanism to control, so that the service for the second request mode can also be done under low power.

In general, we can use a thread pool to solve this problem, first, when the service is started, we can start several threads, and a container (such as the thread pool) to manage these threads.

When the request arrives, you can take a thread out of the pool, perform the task (usually the response to the request), and then put the thread in the pool after the task is finished;

If the request arrives and there are no idle threads in the pool, the request needs to be queued. Finally, the pool can be destroyed when the service is closed.

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

Thread pooling technology is a technology that focuses on how to shorten or adjust t1,t3 time, 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 threads in the thread pool.

If the server does not use the thread pool to process these requests, the total number of threads is 50000. 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 rational use of a thread pool can bring three benefits:

First: Reduce resource consumption. Reduces the consumption caused by thread creation and destruction by reusing threads that have already been created.

Second: Improve response speed. When a task arrives, the task can be executed immediately without waiting for the thread to be created.

Third: Improve the manageability of the thread. Thread is a scarce resource, if unlimited creation, will not only consume system resources, but also reduce the stability of the system, the use of thread pool can be unified allocation, tuning and monitoring.

But to make the best use of the thread pool, the principle must be at your fingertips.

Inheritance schema for the 2 thread pool

The cost of starting a new thread for a program is relatively high because it involves interacting with the operating system. Using a thread pool can improve performance, especially when you want to create a large number of short-lived threads in your program, and you should consider using a thread pool as well.

The line Cheng Chili each thread code ends and does not die, but returns to the thread pool again as idle, waiting for the next object to be used.

Before JDK5, we had to manually implement our own thread pool, starting with the JDK5, Java built-in support thread pool

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. The following diagram fully describes the class architecture of the thread pool.

Executor is a top-level interface that declares only one method execute (Runnable), the return value is void, and the argument is a Runnable type, which can be understood literally, and is used to perform the assigned task;

The Executorservice interface then inherits the executor interface and declares a number of methods: Submit, InvokeAll, Invokeany, and shutdown;

The abstract class Abstractexecutorservice implements the Executorservice interface and realizes all the methods declared in Executorservice.

Then Threadpoolexecutor inherits the class Abstractexecutorservice.

Mark 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 principle is not clear, it is possible that the configured thread pool is not superior.

As a result, some static factories are provided in the executors class, generating some common thread pools.

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.

Newfixedthreadpool: Creates 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.

Newcachedthreadpool: Creates a cache-able thread pool. If the thread pool is larger than the threads needed to process the task, the thread that is partially idle (60 seconds of not performing a task) is reclaimed.

When the number of tasks increases, the thread pool can also intelligently add new threads to handle tasks.

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.

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

Newsinglethreadexecutor: Create a single-threaded thread pool. This thread pool supports the need for timing and periodic execution of tasks.

The return value of these methods is the Executorservice object, which represents a thread pool that can execute runnable objects or threads represented by callable objects.

It provides the following ways to submit a task:

Future<?> Submit (Runnable Task)

<T> future<t> Submit (callable<t> Task)

Callable and Runable, see the following:

03 创建线程的第3式  02 如何创建线程 线程并发与synchornized   3 使用线程池步骤及案例

The benefit of the thread pool: the line Cheng Chili each thread code ends and does not die, but returns to the thread pool again as idle, waiting for the next object to be used.

How do I implement a thread's code?

A: Create a thread pool object that controls how many thread objects to create.

public static Executorservice newfixedthreadpool (int nthreads)

B: Threads of this thread pool can execute:

A thread that can execute a Runnable object or a callable object

Do a class to implement the Runnable interface.

C: The following methods can be invoked

Future<?> Submit (Runnable Task)

<T> future<t> Submit (callable<t> Task)

D: I'm going to finish, okay? OK.

1 package com.jt.thread.demo05;
 2 
 3 import java.util.concurrent.ExecutorService;
 4 Import java.util.concurrent.Executors;
 5 
 6 Class Myrunnable implements Runnable {
 7     @Override
 8 public     void Run () {
 9 for         (int x = 0 ; x < 100; X + +) {             System.out.println (Thread.CurrentThread (). GetName () + ":" + x);
All} is public 
class Executorservicedemo {public     static void Main (string[] args) {      //Create a thread pool object that controls how many thread objects to create.      //public static executorservice newfixedthreadpool (int nthreads)      Executorservice pool = Executors.newfixedthreadpool (2);      the thread      pool.submit (New myrunnable ()) represented by the Runnable object or callable object can be executed.      Pool.submit (New myrunnable ());     //End thread pool     pool.shutdown ();    }

Run Result:

pool-1-thread-1:0

Pool-1-thread-1:1

Pool-1-thread-1:2

pool-1-thread-2:0

Pool-1-thread-2:1

Pool-1-thread-2:2

Pool-1-thread-2:3

。。。

Description:

(1 Newfixedthreadpool

is a fixed size thread pool There are results visible we specify 2 at run time only 2 threads work

If one of the threads is abnormal, a new thread will replace him.

(2 Shutdown method has 2 overloads:

void shutdown () starts a sequential shutdown, waits for the previously committed task to complete, but does not accept new tasks.

List<runnable> Shutdownnow () attempts to stop all active tasks immediately, suspends processing of waiting tasks, and returns a list of tasks waiting to be executed.

(3 Submit and Execute

3.1 Submit is a method in Executorservice to submit a task

His return value is the future object that can get the execution result

<T> future<t> Submit (callable<t> Task) a task that submits a return value is used for execution, and returns a Future that represents the pending result of the task.

Future<?> Submit (Runnable Task) submits a Runnable task for execution and returns a Future that represents the task.

<T> future<t> Submit (Runnable task, T result) submits a Runnable task for execution, and returns a Future that represents the task.

Related Article

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.