One, thread pool usage scenariosA short processing time for a single task will require a large number of tasks to be processed
second, the use of Java thread pool benefits
1. The disadvantage of creating threads using new Thread (): creating objects every time through new thread () is poorly performing. Threads lack unified management, may create unlimited new threads, compete with each other, and may consume too much system resources to cause panic or oom. Lack of additional functionality, such as timed execution, regular execution, and thread disruption.
2. The benefits of using the Java thread pool: Reusing existing threads, reducing the overhead of object creation, extinction, and improving performance. It can effectively control the maximum number of concurrent threads, improve the utilization rate of system resources, and avoid excessive resource competition and avoid clogging. It provides functions such as timed execution, regular execution, single thread, concurrent number control. java four kinds of thread pools
The top-level interface in the Java thread pool is Executor, but in the strictest sense Executor is not a thread pool, but a tool for executing threads. The real thread pool interface is Executorservice. The following diagram fully describes the class architecture of the thread pool:
1. Newcachedthreadpool
Create a thread pool that can create new threads as needed, but reuse them when previously constructed threads are available. These thread pools generally improve program performance for programs that perform many short-term asynchronous tasks. Calling execute reuses the previously constructed thread (if the thread is available). If an existing thread is not available, create a new thread and add it to the pool. Terminates and removes threads from the cache that have not been used for 60 seconds. Therefore, a thread pool that remains idle for a long time does not use any resources.
Public static Executorservice Newcachedthreadpool ()
Sample code:
public class Threadpoolexecutortest {public
static void Main (string[] args) {
executorservice Cachethreadpool =executors.newcachedthreadpool ();
for (int i =1;i<=5;i++) {
final int index=i;
try{
thread.sleep (1000);
} catch (Interruptedexception e) {
e.printstacktrace ();
}
Cachethreadpool.execute (New Runnable () {
@Override public
void Run () {
System.out.println ("the first" +index + ' Thread ' +thread.currentthread (). GetName ())
;}} Output
1th thread pool-1-thread-1
2nd thread pool-1-thread-1
3rd thread pool-1-thread-1
4th thread pool-1-thread-1 5th Thread Pool-1-thread-1
The result shows that when the first task is completed when the second task is performed, the thread that executes the first task is reused instead of creating a new thread at a time.
2. Newfixedthreadpool
Creates a thread pool that specifies the number of worker threads. Whenever a task is committed, a worker thread is created, and if the number of worker threads reaches the maximum number of thread pool initial, the committed task is saved to the pool queue.
Public static Executorservice newfixedthreadpool (int nthreads)
nthreads-Number of threads in pool
Sample code:
public class Threadpoolexecutortest {public
static void Main (string[] args) {
Executorservice Fixedthreadpool =executors. Newfixedthreadpool (3);
for (int i =1; i<=5;i++) {
final int index=i;
Fixedthreadpool.execute (New Runnable () {
@Override public
void Run () {
try {
System.out.println The first "+index +" thread "+thread.currentthread (). GetName ());
Thread.Sleep (1000);
} catch (Interruptedexception e) {
E. Printstacktrace ();
}
}}}
Because you set the maximum number of threads to 3, you wait 2 seconds after outputting three digits before continuing the output.
2. Newscheduledthreadpool
Creates a thread pool that can schedule commands to run or execute periodically after a given delay.
Public static Scheduledexecutorservice newscheduledthreadpool (int corepoolsize)
Corepoolsize-The number of threads saved in the pool, even if the thread is idle.
deferred execution of sample code :
public class Threadpoolexecutortest {public
static void Main (string[] args) {
scheduledexecutorservice Scheduledthreadpool= Executors.newscheduledthreadpool (3);
Scheduledthreadpool.schedule (Newrunnable () {
@Override public
void Run () {
System.out.println (delay three seconds);
}
}, 3, timeunit.seconds);
}
Indicates a delay of 3 seconds for execution.
Execute sample code on a regular basis :
public class Threadpoolexecutortest {public
static void Main (string[] args) {
scheduledexecutorservice Scheduledthreadpool= Executors.newscheduledthreadpool (3);
Scheduledthreadpool.scheduleatfixedrate (Newrunnable () {
@Override public
void Run () {
System.out.println ("Execute once every three seconds after 1 seconds");}
},1,3,timeunit.seconds;}
Indicates that the delay is performed every 3 seconds after 1 seconds.
4.newSingleThreadExecutor
Create a Executor that uses a single worker thread to run the thread in a unbounded queue. (Note that if this individual thread is terminated because of a failure during execution prior to shutdown, a new thread will perform the successor task if needed). Each task is guaranteed to be performed sequentially, and no multiple threads are active at any given time. Unlike other equivalent Newfixedthreadpool (1), it is guaranteed that other threads can be used without reconfiguring the execution program returned by this method.
Public static Executorservice Newsinglethreadexecutor ()
Sample Code :
public class Threadpoolexecutortest {public static void main (string[] args) {Exe
Cutorservice singlethreadpool= executors.newsinglethreadexecutor ();
for (int i=1;i<=5;i++) {int index=i;
Singlethreadpool.execute (New Runnable () {@Override public void run () {
try{System.out.println ("The first" +index+ "Threads");
Thread.Sleep (2000);
}catch (interruptedexception e) {e.printstacktrace ();
}
} }); }
}
}