Use of four Java thread pools and four java threads
Java thread pool monitoring
Java provides four thread pools through Executors:
NewCachedThreadPool creates a cache thread pool. If the thread pool length exceeds the processing requirement, Idle threads can be recycled flexibly. If no thread pool length exists, a new thread is created.
NewFixedThreadPool creates a fixed-length thread pool, which can control the maximum number of concurrent threads. threads that exceed the limit 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. It only uses a unique worker thread to execute tasks, ensuring that all tasks are executed in the specified Order (FIFO, LIFO, priority.
(1) newCachedThreadPool
Create a cache thread pool. If the thread pool length exceeds the processing requirement, free threads can be recycled flexibly. If no thread pool can be recycled, a new thread is created. The sample code is as follows:
Java code
The thread pool is infinite. When the second task is executed and the first task is completed, the thread for executing the first task is reused instead of creating a new thread each time.
(2) newFixedThreadPool
Create a fixed-length thread pool to control the maximum number of concurrent threads. threads that exceed the limit will wait in the queue. The sample code is as follows:
Java code
Because the thread pool size is 3 and each task outputs an index and sleep for 2 seconds, three numbers are printed every two seconds.
It is best to set the size of the fixed-length thread pool based on system resources. Such as Runtime. getRuntime (). availableProcessors ()
(3) newScheduledThreadPool
Creates a fixed-length thread pool that supports scheduled and periodic task execution. Example code of delayed execution:
Java code
The execution is delayed by 3 seconds.
Periodically execute the following sample code:
Java code
It indicates that the task is executed every 3 seconds after a delay of 1 second.
(4) newSingleThreadExecutor
Create a single-threaded thread pool. It only uses a unique worker thread to execute tasks and ensures that all tasks are executed in the specified order (FIFO, LIFO, priority. The sample code is as follows:
Java code
The results are output in sequence, which is equivalent to executing each task in sequence.
You can use the JDK monitoring tool to monitor the number of threads we have created, run a non-terminating thread, and create a specified number of threads to observe:
Tool directory:C: \ Program Files \ Java \ jdk1.6.0 _ 06 \ bin \ jconsole.exe
Slightly modify the running program:
Java code
The effect is as follows:
Select the program we run:
Monitor running status