Use of the Java---thread pool

Source: Internet
Author: User

What does the 1 thread pool do?

Network requests usually have two forms:

First, the request is not very frequent, and each connection will remain for a considerable period of time to read data or write data, and finally disconnected, such as file download, network streaming media.

Another form is frequent requests, but the connection is disconnected after a small amount of data is read/written. Given the concurrency of the service, if each request comes in after the service starts a thread for it, the resources for the service can be wasteful, especially in the second case.

Because it is usually time-consuming to create a thread, set this time to T1, and after the read/write service is T2, when t1>>t2, we should consider a strategy or mechanism to control, so that the service for the second way of request can be done at a lower power consumption.

In general, we can use the thread pool to solve this problem, first of all, when the service starts, we can start several threads and use a container (such as a 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 is destroyed when the service shuts down.

Multithreading technology mainly solves the problem of multiple threads 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 takes a task to complete: T1 creates a thread time, T2 the time to execute a task in the thread, T3 destroys the threading time.
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, thus improving the performance of server programs.

It t1,t3 the start and end of the server program, or some idle time period, so that there is no t1,t3 overhead when the server program processes the client request.

The thread pool not only adjusts the time period generated by the 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. Thread pools, the number of threads is generally fixed, so the total number of threads does 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 the thread pool do not waste time processing requests in order to create 50000, thereby increasing efficiency.

The rational use of the thread pool can bring three benefits:

First: reduce resource consumption . Reduce the consumption caused by thread creation and destruction by reusing the threads that have 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 threads. Threads are scarce resources that, if created indefinitely, not only consume system resources, but also reduce system stability, using a thread pool for uniform allocation, tuning, and monitoring.

But to make reasonable use of the thread pool, it must be well-versed in its principles.

2 Thread Pool Inheritance schema

Program startup a new thread cost 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 lot of short-lived threads in your program.

Line constructor Each thread code ends and does not die, but returns to the thread pool again to become idle, waiting for the next object to be used.

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

The top interface of the thread pool in Java is executor, but strictly speaking, executor is not a thread pool, but a tool for executing threads. The real thread pool interface is executorservice.

Executor is a top-level interface in which only one method execute (Runnable) is declared, the return value is void, the argument is of type Runnable, and is literally understood to be used to perform the task passed in;

To configure a thread pool is more complex, especially if the thread pool principle is not very clear, it is likely that the thread pool configured is not a better one.

As a result, some static factories are provided inside the executors class to generate some common thread pools:

Newsinglethreadexecutor: Creates a single thread pool. This thread pool has only one thread at work, which is equivalent to single-threaded serial execution of all tasks.

If this unique thread ends because of an exception, a new thread will replace it. This thread pool guarantees that the order in which all tasks are executed is performed in the order in which the tasks are submitted.

Newfixedthreadpool: Creates a fixed-size thread pool. Each time a task is committed, a thread is created until the thread reaches the maximum size of the threads pool.

Once the maximum size of the thread pool is reached, the thread pool will be replenished with a new thread if it ends up executing an exception.

Newcachedthreadpool: Creates a cacheable thread pool. If the size of the thread pool exceeds the thread required to process the task, a partially idle (60 second non-performing task) thread is reclaimed.

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

This thread pool does not limit the size of the thread pool, and the thread pool size is entirely dependent on the maximum thread size that the operating system (or JVM) can create.

newscheduledthreadpool: Create a thread pool of unlimited size. This thread pool supports the need to schedule and periodically perform tasks.

Newsinglethreadexecutor: Creates a single thread pool. This thread pool supports the need to schedule and periodically perform tasks.

3 using thread pool steps and Cases

Thread Pool Benefits: line constructor after each thread code ends, and does not die, but returns to the thread pool again to become idle, waiting for the next object to be used.

How do you implement thread code?

A: Create a thread pool object that controls the creation of several thread objects.

public static Executorservice newfixedthreadpool (int nthreads)

B: Threads of this thread pool can execute:

Can execute Runnable object or thread represented by callable object

Do a class to implement the Runnable interface.

C: Call the following method to

Future<?> Submit (Runnable Task)

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

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

Import Java.util.concurrent.ExecutorService;

Import java.util.concurrent.Executors;

Class Myrunnable implements runnable{

public void Run () {

for (int x=0;x<100;x++) {

System.out.println (Thread.CurrentThread (). GetName () + ":" +x);

}

}

}

public class executorservicedemo{

public static void Main (String[]args) {

// creates a thread pool object that controls the creation of several thread objects.

Executorservice Pool=executors.newfixedthreadpool (2);

// can execute runnable object or thread represented by callable object

Pool.submit (New myrunnable ());

Pool.submit (New myrunnable ());

// end thread pool

Pool.shutdown ();

}

}

Description

(1 Newfixedthreadpool

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

If there is a thread exception, there will be a new thread to replace him.

(2 Shutdown method has 2 overloads:

void shutdown () starts a sequential shutdown, waiting for the completed task to be executed, but does not accept new tasks.

List<runnable> Shutdownnow () tries to stop all active tasks immediately, pauses processing of the awaited task, and returns a list of tasks waiting to be executed.

(3 Submit and Execute

3.1 Submit is a method used in Executorservice to submit a task

His return value is the future object can get the results of the execution

<T> future<t>submit (callable<t> Task) submits a task that returns a value for execution, returning 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 (Runnabletask, T result) submits a Runnable task for execution and returns a future that represents the task.

3.2 Execute is a method of the executor interface

Although he could have a task executed like submit, but not a return value.

void Execute(Runnable command)

Executes the given command at some time in the future. The command may be executed in a new thread, a thread that is in the pool, or a thread that is being invoked, as determined by the Executor implementation.

(4Future

The future represents the result of an asynchronous calculation.

It provides a way to check whether the calculation is complete, to wait for the calculation to complete, and to get the results of the calculation.

You can only use the Get method to get the results after the calculation is complete and, if necessary, block this method before the calculation is complete.

Cancellation is performed by the Cancel method. Other methods are provided to determine whether the task is completed properly or canceled. Once the calculation is complete, you can no longer cancel the calculation.

If you use the future for the sake of cancellation and do not provide the available results, you can declare the Future<?> form type and return null as the result of the underlying task.

The future is to cancel the execution result of the specific runnable or callable task, whether the query is completed, and the result is obtained.

If necessary, the result of the execution can be obtained through the Get method, which blocks until the task returns the result.

This means that the future offers three functions:

--To determine whether the task is completed;

-Ability to interrupt tasks;

--Ability to get task execution results.

A Boolean cancel (Boolean mayinterruptifrunning) attempted to cancel the execution of this task.

V get () waits for the calculation to complete if necessary, and then obtains its result.

V get (long timeout, timeunit unit) If necessary, wait up to the time that the calculation is given to complete, if the result is available.

Boolean iscancelled () returns True if it is canceled before the task is completed properly.

Boolean IsDone () returns True if the task is completed.

4 thread pool simple use case 2

The API for the Java.util.concurrent.Executors class provides a number of static methods for creating connection pools:

Import java.concurrent.Executors;

Import Java.concurrent.ExecutorService;

public class javathreadpool{

public static void Main (String[]args) {

Create a thread pool that can be reused for a fixed number of threads

Executorservice Pool=executor.newfixedthreadpool (2);

Create implement Runnable interface object, thread object of course also implements Runnable interface

Thread t1=new MyThread ();

Thread t2=new MyThread ();

Thread t3=new MyThread ();

Thread t4=new MyThread ();

Thread t5=new MyThread ();

Putting a thread into a pool for execution

Pool.execute (t1);

Pool.execute (T2);

Pool.execute (T3);

Pool.execute (T4);

Pool.execute (T5);

Close the thread pool

Pool.shutdown ();

}

}

Class MyThread extends thread{

public void Run () {

System.out.println (Thread.CurrentThread (). GetName () + "executing ....");

}

}

5 single-Task thread pool:

Create a Executor that uses a single worker thread to run the thread in a unbounded queue.

Executorservice pool = Executors.newsinglethreadexecutor ();

Import java.util.concurrent.Executors;

Import Java.uti.concurrent.ExecutorService;

public class singthreadpolldemo{

public static void Main (Stringp[]args) {

// Create a Executor that uses a single worker thread to run the thread in a unbounded queue.

Executorservice Pool=executors.newsinglethreadexecutor ();

Runnable task1=new singletask ();

Runnable task2=new singletask ();

Runnable task3=new singletask ();

Pool.execute (TASK1);

Pool.execute (TASK2);

Pool.execute (TASK3);

Pool.shutdown ();

}

}

Class Singletask implements runnable{

public void Run () {

System.out.println (Thread.CurrentThread (). GetName () + "executing ...");

try{

Thread.Sleep (3000);

}catch (Interruptedexception e) {

E.printstacktrace ();

}

System.out.println (Thread.CurrentThread (). GetName () + "execution complete");

}

}

Use of the Java---thread pool

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.