Home  >  Article  >  Java  >  Java Concurrency Package: Four thread pools provided by Java through Executors

Java Concurrency Package: Four thread pools provided by Java through Executors

php是最好的语言
php是最好的语言Original
2018-08-01 11:53:301670browse

Java four thread pools newCachedThreadPool, newFixedThreadPool, newScheduledThreadPool, newSingleThreadExecutor

Disadvantages of new Thread

a. The performance of each new Thread new object is poor .
b. Threads lack unified management, and there may be unlimited new threads, competing with each other, and may occupy too many system resources, causing crashes or OOM.
c. Lack of more functions, such as scheduled execution, periodic execution, and thread interruption.
Compared with new Thread, the benefits of the four thread pools provided by Java are:
a. Reuse existing threads, reduce the cost of object creation and death, and have good performance.
b. It can effectively control the maximum number of concurrent threads, improve the usage of system resources, and avoid excessive resource competition and congestion.
c. Provide functions such as scheduled execution, periodic execution, single thread, and concurrency control.

Java provides four thread pools through Executors, which are:
newCachedThreadPool creates a cacheable thread pool. If the length of the thread pool exceeds processing needs, idle threads can be flexibly recycled. If there is no recycling, create a new one. thread.
newFixedThreadPool creates a fixed-length thread pool that can control the maximum number of concurrent threads. Exceeding threads will wait in the queue.
newScheduledThreadPool creates a fixed-length thread pool that supports scheduled and periodic task execution.
newSingleThreadExecutor creates a single-threaded thread pool, which will only use a unique worker thread to execute tasks, ensuring that all tasks are executed in the specified order (FIFO, LIFO, priority).

(1). newCachedThreadPool
Create a cacheable thread pool. If the length of the thread pool exceeds processing needs, idle threads can be flexibly recycled. If there are no more If recycled, a new thread will be created. The sample code is as follows:

ExecutorService cachedThreadPool = Executors.newCachedThreadPool();for (int i = 0; i < 10; i++) {final int index = i;try {Thread.sleep(index * 1000);} catch (InterruptedException e) {e.printStackTrace();} cachedThreadPool.execute(new Runnable() { @Overridepublic void run() {System.out.println(in
dex);}});}

The thread pool is infinite. When the second task is executed, the first task has been completed, and the thread executing the first task will be reused without creating a new thread each time.

(2). newFixedThreadPool
Create a fixed-length thread pool that can control the maximum number of concurrent threads. Exceeding threads will wait in the queue. The sample code is as follows:

ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
for (int i = 0; i < 10; i++) {
final int index = i;
fixedThreadPool.execute(new Runnable() {
 
@Override
public void run() {
try {
System.out.println(index);
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}

Because the thread pool size is 3, each task sleeps for 2 seconds after outputting the index, so 3 numbers are printed every two seconds.

The size of the fixed-length thread pool is best set according to system resources. Such as Runtime.getRuntime().availableProcessors(). Please refer to PreloadDataCache.

(3) newScheduledThreadPool
Create a fixed-length thread pool to support scheduled and periodic task execution. The sample code for delayed execution is as follows: ScheduledExecutorService scheduledThreadPool =

Executors.newScheduledThreadPool(5);
scheduledThreadPool.schedule(new Runnable() {
 
@Override
public void run() {
System.out.println("delay 3 seconds");
}
}, 3, TimeUnit.SECONDS);

means delayed execution for 3 seconds.

The sample code for regular execution is as follows:

scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
 
@Override
public void run() {
System.out.println("delay 1 seconds, and excute every 3 seconds");
}
}, 1, 3, TimeUnit.SECONDS);

means execution every 3 seconds after a delay of 1 second.

ScheduledExecutorService is safer and more powerful than Timer. There will be a separate article for comparison later.

(4), newSingleThreadExecutor
Create a single-threaded thread pool, which will only use the only working thread to execute tasks, ensuring that all tasks follow the specified order (FIFO, LIFO, priority) execution. The sample code is as follows:

ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
for (int i = 0; i < 10; i++) {
final int index = i;
singleThreadExecutor.execute(new Runnable() {
 
@Override
public void run() {
try {
System.out.println(index);
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}

The results are output in sequence, which is equivalent to executing each task in sequence.

Most current GUI programs are single-threaded. Single threads in Android can be used for database operations, file operations, batch installation of applications, batch deletion of applications, and other operations that are not suitable for concurrency but may cause IO blocking and affect the response of the UI thread.

The role of the thread pool:

The role of the thread pool is to limit the number of execution threads in the system.
According to the system environment, the number of threads can be set automatically or manually to achieve the best operation effect; less will waste system resources, and more will cause system congestion and inefficiency. Use the thread pool to control the number of threads, and other threads wait in line. After a task is executed, the frontmost task in the queue is taken and execution begins. If there is no waiting process in the queue, this resource of the thread pool is waiting. When a new task needs to be run, if there are waiting worker threads in the thread pool, it can start running; otherwise, it enters the waiting queue.

Why use a thread pool:

1. Reduce the number of thread creation and destruction, each worker thread can be reused and can perform multiple tasks .

2. You can adjust the number of working threads in the thread pool according to the system's capacity to prevent the server from being exhausted due to excessive memory consumption (each thread requires about 1MB of memory, and the thread starts The more memory is consumed, the more memory will be consumed and eventually the system will crash).

The top-level interface of the thread pool in Java is Executor, but strictly speaking, Executor is not a thread pool, but just a tool for executing threads. The real thread pool interface is ExecutorService.

Related articles:

Detailed explanation of graphic code of thread pool in Java

Detailed explanation of the use of thread pool in java concurrent programming

Related videos:

Java Multithreading and Concurrency Library Advanced Application Video Tutorial

The above is the detailed content of Java Concurrency Package: Four thread pools provided by Java through Executors. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn