A talk on Java in four common thread pool

newFixedThreadPool

First, look at the method of creating such a thread pool:

public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
}

As can be seen from the construction method, which creates a fixed-size thread pool, each commit a task to create a thread, until the thread pool thread to achieve maximum nThreads . After the size of the thread pool once they reach the maximum value, and then there is the *** into the blocking queue when a new job submission, until there is a thread idle, then remove the job from the queue to continue.
So, how to use newFixedThreadPool it? Let's give 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("运行时间: " +
                                sdf.format(new Date()) + " " + index);
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                });
        }

        fixedThreadPool.shutdown(); 
    }
}

In the above example we create a fixed-size thread pool 3, and then submitted five tasks in a thread pool. When submitting the fourth task, because the size of the thread pool has reached 3 and the first three tasks run, so the first four tasks are placed in a queue, waiting to be run again when there are idle thread. Results are as follows (note that the first three tasks, and run time of task 2):

运行时间: 08:09:02 1
运行时间: 08:09:02 2
运行时间: 08:09:02 0
运行时间: 08:09:04 4
运行时间: 08:09:04 3

newCachedThreadPool

First, look at the method of creating such a thread pool:

public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }

As it can be seen from the construction method, which creates a cached thread pool. When a new job submission time, there is an idle thread processing tasks directly, there is no idle thread creates a new thread processing task, the task is not stored in the queue. Thread pool thread pool size do not limit, the size of the thread pool thread entirely dependent on the maximum size of the operating system (or JVM) that can be created. If the thread is idle for more than 60 seconds it will be recovered.
So, how to use newCachedThreadPool it? Let's give 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("运行时间: " +
                                sdf.format(new Date()) + " " + index);
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                });
        }

        cachedThreadPool.shutdown();
    }
}

This thread has since submitted a new task, it will create a new thread (the thread pool is not idle threads), you do not need to wait, so the running time of submission of five tasks are the same, the results are as follows:

运行时间: 08:45:18 2
运行时间: 08:45:18 1
运行时间: 08:45:18 3
运行时间: 08:45:18 4
运行时间: 08:45:18 0

newSingleThreadExecutor

First, look at the method of creating such a thread pool:

public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
}

As it can be seen from the construction method, which creates a single-threaded thread pool, use it only to perform the task only worker threads to ensure that all tasks are performed in a specified order.
So, how to use newSingleThreadExecutor it? Let's give 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("运行时间: " +
                                sdf.format(new Date()) + " " + index);
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                });
        }

        singleThreadExecutor.shutdown();
    }
}

Because the thread pool is similar to the single-threaded execution, so after the first implementation of a task before the finish, and then perform the next task order,
results are as follows:

运行时间: 08:54:17 0
运行时间: 08:54:19 1
运行时间: 08:54:21 2
运行时间: 08:54:23 3
运行时间: 08:54:25 4

Some students may question: Now that is similar to the single-threaded execution, so that the thread pool there exist necessary? Single-threaded execution here refers to the internal thread pool, thread pool from the perspective outside view, the main thread is not blocked when submitting tasks to the thread pool still is asynchronous.

newScheduledThreadPool

This method creates a fixed-size thread pool to support regular and periodic task execution.
First, look at the example of the timing of the implementation of:

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("提交时间: " + sdf.format(new Date()));
        scheduledThreadPool.schedule(new Runnable() {
                @Override
                public void run() {
                    System.out.println("运行时间: " + sdf.format(new Date()));
                }
            }, 3, TimeUnit.SECONDS);
        scheduledThreadPool.shutdown();
    }
}

Using the thread pool schedule method, after a delay of 3 seconds to perform tasks, the results are as follows:

提交时间: 09:11:39
运行时间: 09:11:42

Look at the example of the implementation period:

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("提交时间: " + sdf.format(new Date()));
        scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
                @Override
                public void run() {
                    System.out.println("运行时间: " + sdf.format(new Date()));
                }
            }, 1, 3, TimeUnit.SECONDS);
        Thread.sleep(10000);
        scheduledThreadPool.shutdown();
    }
}

Using the thread pool scheduleAtFixedRate method, delay the execution of the task once every 3 seconds 1 second, the results are as follows:

提交时间: 09:23:20
运行时间: 09:23:21
运行时间: 09:23:24
运行时间: 09:23:27

Guess you like

Origin blog.51cto.com/14570694/2463505