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

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 pool’s limit

Maximum nThreads.

Once the size of the thread pool reaches its maximum, new tasks are submitted and placed in an unbounded blocking queue until there are empty threads

When idle, the task is removed from the queue to continue.

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(" run 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.

The fourth task is submitted because the thread pool size has reached 3 and the first 3 tasks are running

It is queued up to be 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.

No tasks are stored in the queue. There is no limit to the thread pool size, which is completely operating system dependent (or

The maximum thread size that the 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(" run time: "+ sdf.format(new Date()) +" "+ index); Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); }}}); } cachedThreadPool.shutdown(); }}Copy the code

Because this thread has a new task to submit, a new thread is created (when there are no free threads in the thread pool)

There is no 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 will execute any thread with a single worker thread

To ensure 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(" run 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 before the next task is executed in sequence,

The running results are as follows:

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:

Since it is similar to single-threaded execution, is this thread pool still necessary?

Single thread execution here refers to inside the thread pool. From the perspective of outside the thread pool, the main thread does not commit tasks to the thread pool

There is no blocking and it 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(" submit time: "+ sdf.format(new Date())); ScheduledThreadPool. The schedule (new Runnable () {@ Override public void the 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(" submit time: "+ sdf.format(new Date())); ScheduledThreadPool. ScheduleAtFixedRate (new Runnable () {@ Override public void the 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, tasks are executed every 3 seconds after a delay of 1 second

The running results are as follows:

Submitted time: 09:23:20 Run time: 09:23:21 Run time: 09:23:24 Run time: 09:23:27Copy the code

The above interview questions have been compiled into a PDF file, hoping to help you review and find a good job before the interview, and relatively save you time searching for information on the Internet to learn!!

Attached welcome to pay attention to my public variety number: IT resources of the home, scan the following two-dimensional code can receive more first-line large factory Java interview materials!

The last

Welcome to the comments section to communicate and improve each other; Sorting out information is not easy, if you like the article remember to point a zan ha, thank you for your support!!