newFixedThreadPool
First, take a look at how this thread pool is created:
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
Copy the code
As you can see from the constructor, it creates a fixed-size thread pool, creating one thread each time a task is submitted until the thread reaches the maximum value of the thread pool, nThreads. Once the size of the thread pool reaches the maximum, new tasks are put into the unbounded blocking queue when they are submitted. When there are idle threads, the task is removed from the queue to continue execution. So how do you use newFixedThreadPool? Let’s take an example:
public class OneMoreStudy {
public static void main(String[] args) {
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
for (int i = 0; i < 5; i++) {
final int index = i;
fixedThreadPool.execute(new Runnable() {
@Override
public void run() {
try {
SimpleDateFormat sdf = new SimpleDateFormat(
"HH:mm:ss");
System.out.println("Running time:" +
sdf.format(new Date()) + ""+ index); Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); }}}); } fixedThreadPool.shutdown(); }}Copy the code
The above example creates a thread pool of fixed size 3, and then submits five tasks in the thread pool. When the fourth task is submitted, because the thread pool size has reached 3 and the first 3 tasks are running, the fourth task is queued to run when there are free threads. The results are as follows (note the running time of the first 3 tasks and the last 2 tasks) :
Run time: 08:09:02 1 Run time: 08:09:02 2 Run time: 08:09:02 0 Run time: 08:09:04 4 Run time: 08:09:04 3Copy the code
newCachedThreadPool
First, take a look at how this thread pool is created:
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
Copy the code
As you can see from the constructor, it creates a cacheable thread pool. When a new task is submitted, there are idle threads to process the task directly, and there are no idle threads to create a new thread to process the task, and no task is stored in the queue. There is no limit to the thread pool size, which is entirely dependent on the maximum thread size that the operating system (or JVM) can create. Threads that are idle for more than 60 seconds are reclaimed. So how do you use newCachedThreadPool? Let’s take an example:
public class OneMoreStudy {
public static void main(String[] args) {
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
for (int i = 0; i < 5; i++) {
final int index = i;
cachedThreadPool.execute(new Runnable() {
@Override
public void run() {
try {
SimpleDateFormat sdf = new SimpleDateFormat(
"HH:mm:ss");
System.out.println("Running time:" +
sdf.format(new Date()) + ""+ index); Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); }}}); } cachedThreadPool.shutdown(); }}Copy the code
Since this thread has a new task to submit, it creates a new thread (when there are no idle threads in the thread pool) without waiting, so the five submitted tasks take the same running time, with the following results:
Running time: 08:45:182 Running time: 08:45:181 Running time: 08:45:183 Running time: 08:45:184 Running time: 08:45:180Copy the code
newSingleThreadExecutor
First, take a look at how this thread pool is created:
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
Copy the code
As you can see from the constructor, it creates a single-threaded thread pool that only uses a single worker thread to execute tasks, ensuring that all tasks are executed in the specified order. So, how do you use newSingleThreadExecutor? Let’s take an example:
public class OneMoreStudy {
public static void main(String[] args) {
ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
for (int i = 0; i < 5; i++) {
final int index = i;
singleThreadExecutor.execute(new Runnable() {
@Override
public void run() {
try {
SimpleDateFormat sdf = new SimpleDateFormat(
"HH:mm:ss");
System.out.println("Running time:" +
sdf.format(new Date()) + ""+ index); Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); }}}); } singleThreadExecutor.shutdown(); }}Copy the code
Since this thread pool is similar to single-thread execution, the previous task is executed first, and then the next task is executed in sequence, with the following result:
Running time: 08:54:170 Running time: 08:54:191 Running time: 08:54:2122 Running time: 08:54:233 Running time: 08:54:254Copy the code
Some students may question: is there any need for a thread pool since it is similar to single-threaded execution? Single thread execution here refers to inside the thread pool. From the perspective of outside the thread pool, the main thread does not block when submitting tasks to the thread pool and is still asynchronous.
newScheduledThreadPool
This method creates a fixed size thread pool that supports both scheduled and periodic task execution. Let’s start with an example of timed execution:
public class OneMoreStudy {
public static void main(String[] args) {
final SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(3);
System.out.println("Submission Time:" + sdf.format(new Date()));
scheduledThreadPool.schedule(new Runnable() {
@Override
public void run() {
System.out.println("Running time:"+ sdf.format(new Date())); } }, 3, TimeUnit.SECONDS); scheduledThreadPool.shutdown(); }}Copy the code
Using the schedule method of the thread pool, the task is executed after a delay of 3 seconds, with the following result:
Submission time: 09:11:39 Running time: 09:11:42Copy the code
Let’s look at an example of periodic execution:
public class OneMoreStudy {
public static void main(String[] args) {
final SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(3);
System.out.println("Submission Time:" + sdf.format(new Date()));
scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println("Running time:"+ sdf.format(new Date())); } }, 1, 3, TimeUnit.SECONDS); Thread.sleep(10000); scheduledThreadPool.shutdown(); }}Copy the code
Using the scheduleAtFixedRate method of the thread pool, the task is executed every 3 seconds after a delay of 1 second. The result is as follows:
Submitted time: 09:23:20 Run time: 09:23:21 Run time: 09:23:24 Run time: 09:23:27Copy the code