java multithreading: 4, the thread pool concept of the four ways to create, state and other issues

1. What is the thread pool?

java.util.concurrent.Executors java.util.concurrent.Executor provides an implementation of the interface used to create the thread pool. The real thread pool implementation class is ExecutorService.

Thread pool is a form of multi-threaded processing. Add in the task processing queue, and then start these tasks after you create threads, each has a default stack size to default priority run, and in multi-threaded unit.

If a thread in managed code is free, the thread pool thread to be inserted into another assist to keep all processors busy.

If all the thread pool is always kept busy, but the queue contains pending work, the number of helper threads thread pool will never exceed the maximum value over time. Thread exceeds the maximum value can be queued, but they have to wait until after the completion of another thread to start.

The role of the advantages of the thread pool: thread pool can improve the performance of a program to strengthen the unified management of the thread.
(1) reuse of thread pool thread, avoid the creation and destruction caused by thread-locking performance overhead

(2) the effective maximum number of concurrent control thread pool, to avoid among a large number of threads to seize system resources due to obstruction

(3) can be a simple thread management , and provide some specific operations, such as: can provide regular, periodic, single-threaded, concurrent control functions

2, create a thread pool, which has several ways?

(1) newCachedThreadPool-- be cached thread pool process

A thread pool may be cached, if the thread pool is longer than the processing needs, flexibility recovered idle thread, if not recovered, the new thread. But idle threads in the pool has a timeout limit, when the timeout period is 60 seconds, more than 60 seconds of idle thread will be recovered.

Compare for the implementation of a large number of less time-consuming task, when the whole thread pool are idle, the thread pool thread will time-out is stopped . Calls to execute will reuse previously constructed threads (threads if available), it is possible to implement threads reuse.

public class MynewCachedThreadPool {

	public static void main(String[] args) {
		int num = 9; // 线程数
		// CountDownLatch是一个同步辅助类也可以使用AtomicInteger替代
		CountDownLatch doneSignal = new CountDownLatch(num);
		ExecutorService pool = Executors.newCachedThreadPool();
		for (int i = 0; i < num; i++)
			// 在未来某个时间执行给定的命令
			// 这里的CountDownLatch的构造函数中使用的int型变量的意思是需要等待多少个操作 的完成。
			pool.execute(new WorkerRunnable(doneSignal, i));
		try {
			doneSignal.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		// 子线程执行完毕,可以开始后续任务处理了
		System.out.println("所有任务执行完毕");

	}
}

class WorkerRunnable implements Runnable {
	private final CountDownLatch doneSignal;// 同步辅助类
	private final int i;// 计数

	WorkerRunnable(CountDownLatch doneSignal, int i) {
		this.doneSignal = doneSignal;
		this.i = i;
	}

	public void run() {
		// 子线程的任务
		try {
			doWork(i);
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 任务执行完毕递减锁存器的计数
		doneSignal.countDown();
	}

	void doWork(int i) {
		System.out.println("这是第" + (i + 1) + "个任务");
	}
}

(2) newFixedThreadPool - Specifies the number of worker threads the thread pool

Specifies the number of worker threads to create a thread pool. Whenever submit a task to create a worker thread, if the number of worker threads the thread pool reaches the maximum number of initial tasks will be submitted to the pool into the queue.

Thread pool has the advantage of improving program efficiency and save money when creating the thread consumption. However, when the thread pool idle, that is, when the thread pool is not runnable tasks, it will not release the worker, but also take up some system resources.

(3) newScheduledThreadPool - fixed-length thread pool

Create a fixed-size thread pool, but also support the timing and periodicity of task execution, support and regular periodic task execution. Create a fixed-size thread pool, but also support the timing and periodicity of task execution, support and regular periodic task execution.
Contrast can analyze the Timer class.

(4) newSingleThreadExecutor - single-threaded thread pool

Creating a single threaded Executor, that is, only to create a unique worker thread to perform the task, it will only be to perform the task with the only worker threads to ensure that all tasks are performed in a specified order (FIFO, LIFO, priorities).
If this thread abnormal end, there will be another to replace it, ensure the implementation of the order. The greatest feature of the single worker thread is guaranteed to perform various tasks in sequence, and at any given time there will be no more than one thread is active.

3, the thread pool, which has several state?

There are five kinds of thread pool status: Running (running), ShutDown (shutdown), Stop (stop), Tidying (finishing), Terminated (terminated).
Here Insert Picture Description
(1) Running
can receive new tasks, and the task has been added for processing.

(2) ShutDown
does not receive a new task, but it can handle tasks that have been added.
The calling thread pool shutdown () interface, the status of running into the thread pool shutdown.

(3) Stop
does not receive a new task, do not handle the task has been added, and interrupt the task being processed.
The calling thread pool shutdownNow () interface, the thread pool or shutdown of running into stop.

(4) Tidying
When all tasks have been terminated, the number of tasks ctl record is 0, the thread pool becomes TIDYING state. When the thread pool becomes Tidying state, will perform hook function terminated (). terminated () is empty in ThreadPoolExecutor class, when the user wants to thread pool becomes Tidying, performs corresponding processing; may be achieved by overloading terminated () function.
When the thread pool in a shutdown state, blocking the queue is empty and the task execution thread pool is also empty, it will by the shutdown into Tidying.
When the thread pool in the Stop state, the task execution thread pool is empty, it will be converted by the Stop Tidying.

(5) Terminated
thread pool completely terminated.
Tidying state in the thread pool, after the execution terminated (), it will be converted by the Tidying Terminated state.

4. What is the difference in the thread pool submit () and excute () method?

(1) belongs to a different interface.
submit (Callable task), submit ( Runnable task, T result), submit (Runnable task) ExecutorService assigned to the interface.

execute (Runnable command) assigned to Executor interface. ExecutorService inherited the Executor.

(2) whether there is a return value.
submit () return a value.
execute no return value.

(3) exception caught.
submit () easy to do exception handling. The Future.get by () may capture exception.

Published 57 original articles · won praise 13 · views 1096

Guess you like

Origin blog.csdn.net/weixin_42924812/article/details/105209914