Nine, summary basis of java multithreading thread pool

First, what is the thread pool

1.Java in line Cheng pool is the use of field scene up and hair frameworks, and almost all require asynchronous or send execute the line of any business program can use line Cheng pool. In the open sent a process, rational use of the line path cell can be tape to . 3 a good place .
First: reduce funding sources consumption . Pass through reuse already creating built -line process to reduce line drive record construction of pin destroyed consumption caused.
Second: to improve the response should speed . When any task arrival time , any task may not be required to wait until the lineCheng Chong Jian will be able to immediately execute the line.
Third: improve lines manageable process . Line process are scarce resources source, if unrestricted creating built, not only consumes system system resource source, but also reduces the system the system 's stability characterization using wire path cell may feed line system a distribution tuning and monitoring controls. However, to achieve rational use of line Cheng pool, it will be required for its realization principle well known.

Second, the role of the thread pool

1. The thread pool is a sudden outbreak of a large number of threads designed by a limited number of fixed thread for a large number of operational services, reducing the time required to create and destroy threads, to improve efficiency. If a thread is very long, there is no need to use the thread pool (not can not operate for a long time, but should not.) Moreover, we can not control start threads in the thread pool, suspended, and the suspension.

Third, the classification of the thread pool

1.Java is inherently supports concurrent language, means that support concurrent multi-threading, thread frequently created in high concurrency and large amount of data is very resource consuming, as java provides a thread pool. In jdk1.5 previous versions, and use the thread pool is simple, but after JDK1.5, has been greatly improved. Joined the java.util.concurrent package after JDK1.5, java.util.concurrent package was added to give developers a great help develop a concurrent program and solve concurrency problems. And Executor interface, Executor interface as though a very old interface (released JDK1.5 2004 years) under a contract under this article describes, but many programmers for some of the principles of which are still not familiar with, so write this article to introduced to the Executor interface, at the same time consolidating their knowledge. If there is an error in the article, welcome to point out.

Topmost Executor framework of implementation is ThreadPoolExecutor class, newScheduledThreadPool Executors factory class provided, newFixedThreadPool, newCachedThreadPool fact, only a constructor method parameters ThreadPoolExecutor is different. Passing through different parameters, the thread pool can be constructed for different scenarios under, then its underlying principle is how to achieve it, to introduce this process to run under ThreadPoolExecutor thread pool.

corePoolSize: the size of the core pool. When there are tasks to later, it will create a thread to perform the task, when the number of threads in the thread pool reaches corePoolSize, the task will reach into the cache queue among
maximumPoolSize: The maximum number of threads in the thread pool, it said in the thread pool how many threads can create up;
keepAliveTime: indicates that the thread does not keep long time up to the task execution will be terminated.
unit: keepAliveTime parameter time unit, there are seven values, there are seven kinds TimeUnit static properties in the class;

Four, four kinds of way to create a thread pool

1.Java offers four thread pool by Executors (jdk1.5 and contract), respectively:

1.1.newCachedThreadPool create a cache thread pool, thread pool longer than if treatment needs, the flexibility to reclaim idle thread, if not recyclable, the new thread.

// 无限大小线程池 jvm自动回收
		ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
		for (int i = 0; i < 10; i++) {
			final int temp = i;
			newCachedThreadPool.execute(new Runnable() {

				@Override
				public void run() {
					try {
						Thread.sleep(100);
					} catch (Exception e) {
						// TODO: handle exception
					}
					System.out.println(Thread.currentThread().getName() + ",i:" + temp);

				}
			});
		}

 Summary :  the thread pool is infinite, the first task has been completed when the second task, the thread used to perform the first task will be complex, rather than each time a new thread.

1.2.newFixedThreadPool create a fixed-size thread pool, you can control the maximum number of concurrent threads, excess threads will wait in the queue.

ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(5);
		for (int i = 0; i < 10; i++) {
			final int temp = i;
			newFixedThreadPool.execute(new Runnable() {

				@Override
				public void run() {
					System.out.println(Thread.currentThread().getId() + ",i:" + temp);

				}
			});
		}

Summary: Because the thread pool size of 3, each task outputs index sleep 2 seconds, 3 digital print every two seconds. The size of the fixed-length thread pool the best set according to system resources. The Runtime.getRuntime (). AvailableProcessors ()

 1.3.newScheduledThreadPool create a fixed-size thread pool to support regular and periodic task execution.

ScheduledExecutorService newScheduledThreadPool = Executors.newScheduledThreadPool(5);
		for (int i = 0; i < 10; i++) {
			final int temp = i;
			newScheduledThreadPool.schedule(new Runnable() {
				public void run() {
					System.out.println("i:" + temp);
				}
			}, 3, TimeUnit.SECONDS);
}

Summary: represents a delay three seconds to perform. 

1.4.newSingleThreadExecutor create a single-threaded thread pool, use it only to perform the task only worker threads to ensure that all tasks are performed in a specified order (FIFO, LIFO, priorities).

ExecutorService newSingleThreadExecutor = Executors.newSingleThreadExecutor();
		for (int i = 0; i < 10; i++) {
			final int index = i;
			newSingleThreadExecutor.execute(new Runnable() {

				@Override
				public void run() {
					System.out.println("index:" + index);
					try {
						Thread.sleep(200);
					} catch (Exception e) {
						// TODO: handle exception
					}
				}
			});
		}

Note:  The results sequentially output, equivalent to the implementation of each task order. 

Fifth, the principle of the thread pool

1.corePoolSize (kernel threads): refers to the number of threads practical application.

   maximumPoolSize (maximum number of threads): The number of threads in the thread pool up to create.

2. If the current number of threads in the thread pool is less than corePoolSize, then each to a task, it will create a thread to perform this task;

If the current number of threads in the thread pool> = corePoolSize, then each to a task, will try to add it to the task queue buffer which, if added successfully, the task will be idle threads waiting to execute it out; if the addition failed ( in general the task buffer queue is full), it will try to create a new thread to perform this task;

If the queue is full, the total number of threads on the premise of not more than maximumPoolSize, then create a new thread

If the current number of threads in the thread pool reaches maximumPoolSize, it will take the task deny policy process;

If the number of threads in the pool is greater than corePoolSize, if the idle time exceeds keepAliveTime a thread, the thread will be stopped until the number of threads in the pool is not larger than corePoolSize; if allowed to pool the core thread disposed survival time, then the core cell the thread is idle for more than keepAliveTime, the thread will be terminated.

Six custom thread pool Code

public class Test0007 {

	public static void main(String[] args) {
		// Executors.newCachedThreadPool();
		//提交一个任务到线程池中,线程池的处理流程如下:
		//1、判断线程池里的核心线程是否都在执行任务,如果不是(核心线程空闲或者还有核心线程没有被创建)则创建一个新的工作线程来执行任务。如果核心线程都在执行任务,则进入下个流程。
		//2、线程池判断工作队列是否已满,如果工作队列没有满,则将新提交的任务存储在这个工作队列里。如果工作队列满了,则进入下个流程。
		//3、判断线程池里的线程是否都处于工作状态,如果没有,则创建一个新的工作线程来执行任务。如果已经满了,则交给饱和策略来处理这个任务。

		ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 2, 60L, TimeUnit.SECONDS, new ArrayBlockingQueue<>(3));
		for (int i = 1; i <= 6; i++) {
			TaskThred t1 = new TaskThred("任务" + i);
			executor.execute(t1);
		}
		executor.shutdown();
	}
}

class TaskThred implements Runnable {
	private String taskName;

	public TaskThred(String taskName) {
		this.taskName = taskName;
	}

	@Override
	public void run() {
		System.out.println(Thread.currentThread().getName()+taskName);
	}

}

CONCLUSION OF THE

Always keep the faith!!!

Published 122 original articles · won praise 64 · views 50000 +

Guess you like

Origin blog.csdn.net/chenmingxu438521/article/details/103839690