Java 线程池

系统启动一个线程的成本是比较高的,由于它涉及到与操做系统的交互,使用线程池的好处是提升性能,当系统中包含大量并发的线程时,会致使系统性能剧烈降低,甚至致使JVM崩溃,而线程池的最大线程数参数能够控制系统中并发线程数不超过次数。java

1、Executors 工厂类用来产生线程池,该工厂类包含如下几个静态工厂方法来建立对应的线程池。建立的线程池是一个ExecutorService对象,使用该对象的submit方法或者是execute方法执行相应的Runnable或者是Callable任务。线程池自己在再也不须要的时候调用shutdown()方法中止线程池,调用该方法后,该线程池将再也不容许任务添加进来,可是会直到已添加的全部任务执行完成后才死亡。缓存

一、newCachedThreadPool(),建立一个具备缓存功能的线程池,提交到该线程池的任务(Runnable或Callable对象)建立的线程,若是执行完成,会被缓存到CachedThreadPool中,供后面须要执行的任务使用。并发

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();
        
        //先添加三个任务到线程池
        for(int i = 0 ; i < 3; i++) {
            cacheThreadPool.execute(new Task());
        }
        
        //等三个线程执行完成后,再次添加三个任务到线程池
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        for(int i = 0 ; i < 3; i++) {
            cacheThreadPool.execute(new Task());
        }
    }

}

执行结果以下:dom

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

线程池中的线程对象进行了缓存,当有新任务执行时进行了复用。可是若是有特别多的并发时,缓存线程池仍是会建立不少个线程对象。ide

二、newFixedThreadPool(int nThreads) 建立一个指定线程个数,线程可复用的线程池。函数

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);

        // 先添加三个任务到线程池
        for (int i = 0; i < 5; i++) {
            fixedThreadPool.execute(new Task());
        }

        // 等三个线程执行完成后,再次添加三个任务到线程池
        try {
            Thread.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        for (int i = 0; i < 3; i++) {
            fixedThreadPool.execute(new Task());
        }
    }

}

执行结果:性能

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: 7this

三、newSingleThreadExecutor(),建立一个只有单线程的线程池,至关于调用newFixedThreadPool(1)spa

四、newSheduledThreadPool(int corePoolSize),建立指定线程数的线程池,它能够在指定延迟后执行线程。也能够以某一周期重复执行某一线程,知道调用shutdown()关闭线程池。操作系统

示例以下:

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();
    }

}

运行结果以下:

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

由运行时间可看出,任务是按照5秒的周期执行的。

五、newSingleThreadScheduledExecutor() 建立一个只有一个线程的线程池,同调用newScheduledThreadPool(1)。

2、ForkJoinPool和ForkJoinTask

ForkJoinPool是ExecutorService的实现类,支持将一个任务划分为多个小任务并行计算,在把多个小任务的计算结果合并成总的计算结果。它有两个构造函数

ForkJoinPool(int parallelism)建立一个包含parallelism个并行线程的ForkJoinPool。

ForkJoinPool(),以Runtime.availableProcessors()方法返回值做为parallelism参数来建立ForkJoinPool。

ForkJoinTask 表明一个能够并行,合并的任务。它是实现了Future<T>接口的抽象类,它有两个抽象子类,表明无返回值任务的RecuriveAction和有返回值的RecursiveTask。可根据具体需求继承这两个抽象类实现本身的对象,而后调用ForkJoinPool的submit 方法执行。

RecuriveAction 示例以下,实现并行输出0-300的数字。

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();
    }

}

在拆分小任务后,调用任务的fork()方法,加入到ForkJoinPool中并行执行。

RecursiveTask示例,实现并行计算100个整数求和。拆分为每20个数求和后获取结果,在最后合并为最后的结果。

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();
    }

}

执行结果以下:

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

子任务执行完后,调用任务的join()方法获取子任务执行结果,再相加得到最后的结果。

相关文章
相关标签/搜索