There are four main ways of doing this:
Newfixedthreadpool:
Creates a fixed number of thread pools for reuse of threads. At any time, a maximum of a specified number of threads are running. When more than the specified number of tasks are submitted, the newly submitted task waits until the original task runs.
note, however, that if a single thread fails during execution before it is closed, it will be replaced by a new one if it needs to perform subsequent tasks due to termination .
The thread pool does not stop when it calls shutdown.
Newsinglethreadexecutor:
Create a thread pool with only one thread. (Note: However, note that if a single thread fails during execution before the shutdown, due to termination, if a successor task is required, there will be a new replacement ) The task is guaranteed to be executed sequentially, with only one thread in the pool at any time. Unlike others, such as Newfixedthreadpool (1), you can use other threads without reconfiguring.
Newcachedthreadpool:
Create a thread pool that can create enough threads in the pool if needed, and reuse previously constructed threads if you can. This thread pool can greatly improve the execution efficiency of a short-time asynchronous task. If there are no reusable threads, then one is recreated and added to the pool. If a thread is not in use for 60 seconds, it will be stopped and removed from the pool.
Newscheduledthreadpool:
Create a fixed-line pool that supports handing you the execution of a recurring task.
others are:Newsinglethreadscheduledexecutor:
Creates a thread pool with only a single thread, and threads periodically perform tasks on a recurring basis.
Newworkstealingpool:
Create a thread pool that maintains enough threads to support a given parallel level, and can use multiple queues to reduce contention.
Wait a minute.
Java Thread Pool Learning