Java thread pool and java Thread Pool

Source: Internet
Author: User

Java thread pool and java Thread Pool

The cost of starting a thread by the system is relatively high because it involves interaction with the operating system. The advantage of using the thread pool is to improve performance. When the system contains a large number of concurrent threads, the maximum number of threads in the thread pool can control the number of concurrent threads in the system.

1. Executors factory classes are used to generate thread pools. The factory classes contain the following static factory methods to create corresponding thread pools. The created thread pool is an ExecutorService object that uses the submit method or the execute method of the object to execute the corresponding Runnable or Callable task. The thread pool itself calls the shutdown () method to stop the thread pool when it is no longer needed. After this method is called, the thread pool no longer allows tasks to be added in, however, it will not die until all added tasks are completed.

1. newCachedThreadPool (): Creates a thread pool with the cache function and submits the thread to the thread pool's task (Runnable or Callable object). If the execution is complete, will be cached in the CachedThreadPool for later tasks to be executed.

Import java. util. concurrent. executorService; import java. util. concurrent. executors; public class CacheThreadPool {static class Task implements Runnable {@ Override public void run () {System. out. println (this + "" + Thread. currentThread (). getName () + "AllStackTraces map size:" + Thread. currentThread (). getAllStackTraces (). size () ;}} public static void main (String [] args) {ExecutorService cacheThreadPool = Executors. newCachedThreadPool (); // Add three tasks to the thread pool for (int I = 0; I <3; I ++) {cacheThreadPool.exe cute (new Task ());} // after the execution of the three threads is complete, add the three tasks to the Thread pool try {Thread. sleep (3000);} catch (InterruptedException e) {e. printStackTrace () ;}for (int I = 0; I <3; I ++) {cacheThreadPool.exe cute (new Task ());}}}

The execution result is as follows:

CacheThreadPool$Task@2d312eb9 pool-1-thread-1 AllStackTraces map size: 7CacheThreadPool$Task@59522b86 pool-1-thread-3 AllStackTraces map size: 7CacheThreadPool$Task@73dbb89f pool-1-thread-2 AllStackTraces map size: 7CacheThreadPool$Task@5795cedc pool-1-thread-3 AllStackTraces map size: 7CacheThreadPool$Task@256d5600 pool-1-thread-1 AllStackTraces map size: 7CacheThreadPool$Task@7d1c5894 pool-1-thread-2 AllStackTraces map size: 7

The thread objects in the thread pool are cached and reused when new tasks are executed. However, if there are many concurrent threads, the cache thread pool will still create many thread objects.

2. newFixedThreadPool (int nThreads) creates a thread pool with the specified number of threads and reusable threads.

Import java. util. concurrent. executorService; import java. util. concurrent. executors; public class FixedThreadPool {static class Task implements Runnable {@ Override public void run () {System. out. println (this + "" + Thread. currentThread (). getName () + "AllStackTraces map size:" + Thread. currentThread (). getAllStackTraces (). size () ;}} public static void main (String [] args) {ExecutorService fixedThreadPool = Executors. newFixedThreadPool (3); // first add three tasks to the thread pool for (int I = 0; I <5; I ++) {fixedThreadPool.exe cute (new Task () ;}// after the three threads are executed, add the three tasks to the Thread pool again. try {Thread. sleep (3);} catch (InterruptedException e) {e. printStackTrace () ;}for (int I = 0; I <3; I ++) {fixedThreadPool.exe cute (new Task ());}}}

Execution result:

FixedThreadPool $ Task @ 7045c12d pool-1-thread-2 AllStackTraces map size: 7
FixedThreadPool $ Task @ 50fa0bef pool-1-thread-2 AllStackTraces map size: 7
FixedThreadPool $ Task @ ccb1870 pool-1-thread-2 AllStackTraces map size: 7
FixedThreadPool $ Task @ 7392b4e3 pool-1-thread-1 AllStackTraces map size: 7
FixedThreadPool $ Task @ 5bdeff18 pool-1-thread-2 AllStackTraces map size: 7
FixedThreadPool $ Task @ 7d5554e1 pool-1-thread-1 AllStackTraces map size: 7
FixedThreadPool $ Task @ 24468092 pool-1-thread-3 AllStackTraces map size: 7
FixedThreadPool $ Task @ fa7b978 pool-1-thread-2 AllStackTraces map size: 7

3. newSingleThreadExecutor (): creates a single-threaded thread pool, which is equivalent to calling newFixedThreadPool (1)

4. newSheduledThreadPool (int corePoolSize) is used to create a thread pool with the specified number of threads. It can run the thread after the specified delay. You can also execute a thread repeatedly in a certain cycle to call shutdown () to close the thread pool.

Example:

import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.TimeUnit;public class ScheduledThreadPool {    static class Task implements Runnable {        @Override        public void run() {            System.out.println("time " + System.currentTimeMillis()  + " " + Thread.currentThread().getName() + " AllStackTraces map size: "                    + Thread.currentThread().getAllStackTraces().size());        }    }    public static void main(String[] args) {        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(3);                scheduledExecutorService.schedule(new Task(), 3, TimeUnit.SECONDS);                scheduledExecutorService.scheduleAtFixedRate(new Task(), 3, 5, TimeUnit.SECONDS);            try {            Thread.sleep(30 * 1000);        } catch (InterruptedException e) {            e.printStackTrace();        }        scheduledExecutorService.shutdown();    }}

The running result is as follows:

time 1458921795240 pool-1-thread-1 AllStackTraces map size: 6time 1458921795241 pool-1-thread-2 AllStackTraces map size: 6time 1458921800240 pool-1-thread-1 AllStackTraces map size: 7time 1458921805240 pool-1-thread-1 AllStackTraces map size: 7time 1458921810240 pool-1-thread-1 AllStackTraces map size: 7time 1458921815240 pool-1-thread-1 AllStackTraces map size: 7time 1458921820240 pool-1-thread-1 AllStackTraces map size: 7

The running time shows that the task is executed in a 5-second cycle.

5. newSingleThreadScheduledExecutor () creates a thread pool with only one thread, and CALLS newScheduledThreadPool (1 ).

Ii. ForkJoinPool and ForkJoinTask

ForkJoinPool is the implementation class of ExecutorService. It supports dividing a task into multiple small tasks for Parallel Computing. It combines the computing results of multiple small tasks into the total computing results. It has two Constructors

ForkJoinPool (int parallelism) creates a ForkJoinPool containing parallelism parallel threads.

ForkJoinPool (), which uses the return value of the Runtime. availableProcessors () method as the parallelism parameter to create a ForkJoinPool.

ForkJoinTask indicates a task that can be parallel and merged. It is an abstract class that implements the Future <T> interface. It has two abstract subclasses, representing the RecuriveAction of a task without a returned value and the RecursiveTask of a returned value. You can inherit these two abstract classes as needed to implement your own objects, and then call the ForkJoinPool submit Method for execution.

RecuriveAction example.

import java.util.concurrent.ForkJoinPool;import java.util.concurrent.RecursiveAction;import java.util.concurrent.TimeUnit;public class ActionForkJoinTask {    static class PrintTask extends RecursiveAction {        private static final int THRESHOLD = 50;        private int start;        private int end;        public PrintTask(int start, int end) {            this.start = start;            this.end = end;        }        @Override        protected void compute() {            if (end - start < THRESHOLD) {                for(int i = start; i < end; i++) {                    System.out.println(Thread.currentThread().getName() + " " + i);                }            } else {                int middle = (start + end) / 2;                PrintTask left = new PrintTask(start, middle);                PrintTask right = new PrintTask(middle, end);                left.fork();                right.fork();            }        }    }    public static void main(String[] args) {        ForkJoinPool pool = new ForkJoinPool();                pool.submit(new PrintTask(0,  300));        try {            pool.awaitTermination(2, TimeUnit.SECONDS);        } catch (InterruptedException e) {            e.printStackTrace();        }                pool.shutdown();    }}

After splitting a small task, call the fork () method of the task and add it to ForkJoinPool for parallel execution.

The RecursiveTask example is used to calculate the sum of 100 integers in parallel. Splits the result into the sum of every 20 numbers and merges the result into the final result.

import java.util.Random;import java.util.concurrent.ExecutionException;import java.util.concurrent.ForkJoinPool;import java.util.concurrent.Future;import java.util.concurrent.RecursiveTask;public class TaskForkJoinTask {    static class CalTask extends RecursiveTask<Integer> {        private static final int THRESHOLD = 20;        private int arr[];        private int start;        private int end;        public CalTask(int[] arr, int start, int end) {            this.arr = arr;            this.start = start;            this.end = end;        }        @Override        protected Integer compute() {            int sum = 0;            if (end - start < THRESHOLD) {                for (int i = start; i < end; i++) {                    sum += arr[i];                }                System.out.println(Thread.currentThread().getName() + "  sum:" + sum);                return sum;            } else {                int middle = (start + end) / 2;                CalTask left = new CalTask(arr, start, middle);                CalTask right = new CalTask(arr, middle, end);                left.fork();                right.fork();                return left.join() + right.join();            }        }    }    public static void main(String[] args) {        int arr[] = new int[100];        Random random = new Random();        int total = 0;        for (int i = 0; i < arr.length; i++) {            int tmp = random.nextInt(20);            total += (arr[i] = tmp);        }        System.out.println("total " + total);        ForkJoinPool pool = new ForkJoinPool(4);        Future<Integer> future = pool.submit(new CalTask(arr, 0, arr.length));        try {            System.out.println("cal result: " + future.get());        } catch (InterruptedException e) {            e.printStackTrace();        } catch (ExecutionException e) {            e.printStackTrace();        }        pool.shutdown();    }}

The execution result is as follows:

total 912ForkJoinPool-1-worker-2  sum:82ForkJoinPool-1-worker-2  sum:123ForkJoinPool-1-worker-2  sum:144ForkJoinPool-1-worker-3  sum:119ForkJoinPool-1-worker-2  sum:106ForkJoinPool-1-worker-2  sum:128ForkJoinPool-1-worker-2  sum:121ForkJoinPool-1-worker-3  sum:89cal result: 912

After the sub-task is executed, call the join () method of the task to obtain the execution result of the sub-task, and then add the result to obtain the final result.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.