Java并发编程之线程池及示例

1、Executor

  线程池顶级接口。定义方法,void execute(Runnable)。方法是用于处理任务的一个服务方法。调用者提供Runnable 接口的实现,线程池通过线程执行这个 Runnable。服务方法无返回值的。是 Runnable 接口中的 run 方法无返回值。
  常用方法 -voidexecute(Runnable) 作用是: 启动线程任务的。示例如下:

/**
 * 线程池
 * Executor - 线程池底层处理机制。
 * 在使用线程池的时候,底层如何调用线程中的逻辑。
 */
import java.util.concurrent.Executor;

public class Test_MyExecutor implements Executor {
    public static void main(String[] args) {
        new Test_MyExecutor().execute(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + " - test executor");
            }
        });
    }

    @Override
    public void execute(Runnable command) {
        new Thread(command).start();
    }
}

2、ExecutorService

  Executor 接口的子接口。提供了一个新的服务方法,submit。有返回值(Future 类型)。 submit 方法提供了 overload 方法。其中有参数类型为 Runnable 的,不需要提供返回值的; 有参数类型为 Callable,可以提供线程执行后的返回值。
  Future,是 submit 方法的返回值。代表未来,也就是线程执行结束后的一种结果。如返 回值。
  常见方法 -void execute(Runnable), Future submit(Callable), Future submit(Runnable) 线程池状态: Running, ShuttingDown, Terminated。

    Running- 线程池正在执行中。活动状态。

    ShuttingDown- 线程池正在关闭过程中。优雅关闭。一旦进入这个状态,线程池不再接收新的任务,处理所有已接收的任务,处理完毕后,关闭线程池。

    Terminated- 线程池已经关闭。

3、Future

  未来结果,代表线程任务执行结束后的结果。获取线程执行结果的方式是通过 get 方法获取的。get 无参,阻塞等待线程执行结束,并得到结果。get 有参,阻塞固定时长,等待 线程执行结束后的结果,如果在阻塞时长范围内,线程未执行结束,抛出异常。

  常用方法: T get()、T get(long, TimeUnit) 。

/**
 * 线程池
 * 固定容量线程池
 */
import java.util.concurrent.*;

public class Test_03_Future {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        /*FutureTask<String> task = new FutureTask<>(new Callable<String>() {
            @Override
            public String call() throws Exception {
                return "first future task";
            }
        });
        
        new Thread(task).start();
        
        System.out.println(task.get());*/

        ExecutorService service = Executors.newFixedThreadPool(1);

        Future<String> future = service.submit(new Callable<String>() {
            @Override
            public String call() {
                try {
                    TimeUnit.MILLISECONDS.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("aaa");
                return Thread.currentThread().getName() + " - test executor";
            }
        });
        System.out.println(future);
        System.out.println(future.isDone()); // 查看线程是否结束, 任务是否完成。 call方法是否执行结束

        System.out.println(future.get()); // 获取call方法的返回值。
        System.out.println(future.isDone());
    }
}

4、Callable

  可执行接口。 类似 Runnable 接口。也是可以启动一个线程的接口。其中定义的方法是 call。call 方法的作用和 Runnable 中的 run 方法完全一致。call 方法有返回值。

  接口方法 : Object call();相当于 Runnable 接口中的 run 方法。区别为此方法有返回值。 不能抛出已检查异常。

  Callable、Runnable 接口的选择:需要返回值或需要抛出异常时,使用 Callable;其他情况可任意选择。

5、Executors

  工具类型。为 Executor 线程池提供工具方法。可以快速的提供若干种线程池。如:固定 容量的,无限容量的,容量为 1 等各种线程池。

  线程池是一个进程级的重量级资源。默认的生命周期和 JVM 一致。当开启线程池后, 直到 JVM 关闭为止,是线程池的默认生命周期。如果手工调用 shutdown 方法,那么线程池 执行所有的任务后,自动关闭。

  开始 - 创建线程池。
  结束 - JVM 关闭或调用 shutdown 并处理完所有的任务。 类似 Arrays,Collections 等工具类型的功用。

6、FixedThreadPool

  容量固定的线程池。活动状态和线程池容量是有上限的线程池。所有的线程池中,都有 一个任务队列。使用的是 BlockingQueue<Runnable>作为任务的载体。当任务数量大于线程池容量的时候,没有运行的任务保存在任务队列中,当线程有空闲的,自动从队列中取出任务执行。

  使用场景: 大多数情况下,使用的线程池,首选推荐 FixedThreadPool。OS 系统和硬件是有线程支持上限。不能随意的无限制提供线程池。

  线程池默认的容量上限是 Integer.MAX_VALUE。 常见的线程池容量: PC:200。 服务器:1000~10000

  线程池容量和并发能力换算关系大约为:并发量= 10*线程池容量 ~ 18*线程池容量。

  queued tasks- 任务队列

  completed tasks- 结束任务队列

/**
 * 线程池
 * 固定容量线程池
 * FixedThreadPool - 固定容量线程池。创建线程池的时候,容量固定。构造的时候,提供线程池最大容量
 * Executors.newFixedThreadPool(int) ->  ExecutorService - 线程池服务类型。所有的线程池类型都实现这个接口。
 * 实现这个接口,代表可以提供线程池能力。
 * shutdown - 优雅关闭。 不是强行关闭线程池,回收线程池中的资源。而是不再处理新的任务,将已接收的任务处理完毕后再关闭。
 * Executors - Executor的工具类。类似Collection和Collections的关系,可以更简单的创建若干种线程池。
 */
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Test_02_FixedThreadPool {

    public static void main(String[] args) {
        ExecutorService service =
                Executors.newFixedThreadPool(5);
        for (int i = 0; i < 6; i++) {
            service.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        TimeUnit.MILLISECONDS.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + " - test executor");
                }
            });
        }

        System.out.println(service);

        service.shutdown();
        // 是否已经结束, 相当于回收了资源。
        System.out.println(service.isTerminated());
        // 是否已经关闭, 是否调用过shutdown方法
        System.out.println(service.isShutdown());
        System.out.println(service);

        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // service.shutdown();
        System.out.println(service.isTerminated());
        System.out.println(service.isShutdown());
        System.out.println(service);
    }
}

  执行结果:

java.util.concurrent.ThreadPoolExecutor@71f2a7d5[Running, pool size = 5, active threads = 5, queued tasks = 1, completed tasks = 0]
false
true
java.util.concurrent.ThreadPoolExecutor@71f2a7d5[Shutting down, pool size = 5, active threads = 5, queued tasks = 1, completed tasks = 0]
pool-1-thread-1 - test executor
pool-1-thread-2 - test executor
pool-1-thread-3 - test executor
pool-1-thread-4 - test executor
pool-1-thread-5 - test executor
pool-1-thread-1 - test executor
true
true
java.util.concurrent.ThreadPoolExecutor@71f2a7d5[Terminated, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 6]

  注意:FixedThreadPool实现是基于LinkedBlockingQueue的。

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

7、CachedThreadPool

  缓存的线程池容量不限(Integer.MAX_VALUE)。自动扩容。容量管理策略:如果线程 池中的线程数量不满足任务执行,创建新的线程。每次有新任务无法即时处理的时候,都会 创建新的线程。当线程池中的线程空闲时长达到一定的临界值(默认 60 秒),自动释放线程。

  默认线程空闲 60 秒,自动销毁。
  应用场景: 内部应用或测试应用。 内部应用,有条件的内部数据瞬间处理时应用,如:

  电信平台夜间执行数据整理:有把握在短时间内处理完所有工作,且对硬件和软件有足够的信心。 测试应用:在测试的时候,尝试得到硬件或软件的最高负载量,用于提供 FixedThreadPool 容量的指导。

/**
 * 线程池
 * 无容量限制的线程池(最大容量默认为Integer.MAX_VALUE)
 */
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Test_05_CachedThreadPool {

    public static void main(String[] args) {
        ExecutorService service = Executors.newCachedThreadPool();
        System.out.println(service);

        for (int i = 0; i < 5; i++) {
            service.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        TimeUnit.MILLISECONDS.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + " - test executor");
                }
            });
        }

        System.out.println(service);

        try {
            TimeUnit.SECONDS.sleep(65);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(service);
    }
}

  运行结果:

java.util.concurrent.ThreadPoolExecutor@483bf400[Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0]
java.util.concurrent.ThreadPoolExecutor@483bf400[Running, pool size = 5, active threads = 5, queued tasks = 0, completed tasks = 0]
pool-1-thread-1 - test executor
pool-1-thread-2 - test executor
pool-1-thread-3 - test executor
pool-1-thread-5 - test executor
pool-1-thread-4 - test executor
  注意:CachedThreadPool实现是基于SynchronousQueue的。
public static ExecutorService newCachedThreadPool() {
    return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
}

8、ScheduledThreadPool

  计划任务线程池。可以根据计划自动执行任务的线程池。

scheduleAtFixedRate(Runnable, start_limit, limit, timeunit)

runnable - 要执行的任务。

start_limit - 第一次任务执行的间隔。

limit - 多次任务执行的间隔。

timeunit - 多次任务执行间隔的时间单位。

  使用场景: 计划任务时选用(DelaydQueue),如:电信行业中的数据整理,每分钟整 理,每小时整理,每天整理等。

/**
 * 线程池
 * 计划任务线程池。
 */
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class Test_07_ScheduledThreadPool {

    public static void main(String[] args) {
        ScheduledExecutorService service = Executors.newScheduledThreadPool(3);
        System.out.println(service);

        // 定时完成任务。 scheduleAtFixedRate(Runnable, start_limit, limit, timeunit)
        // runnable - 要执行的任务。
        service.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                try {
                    TimeUnit.MILLISECONDS.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName());
            }
        }, 0, 300, TimeUnit.MILLISECONDS);

    }
}

  运行结果:

java.util.concurrent.ScheduledThreadPoolExecutor@483bf400[Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0]
pool-1-thread-1
pool-1-thread-1
pool-1-thread-2
pool-1-thread-2
pool-1-thread-2

  注意:ScheduledThreadPool实现是基于DelayedWorkQueue的。

public ScheduledThreadPoolExecutor(int corePoolSize) {
    super(corePoolSize, Integer.MAX_VALUE,
         DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
          new DelayedWorkQueue());
}    

9、SingleThreadExceutor

  单一容量的线程池。
  使用场景: 保证任务顺序时使用。如: 游戏大厅中的公共频道聊天。秒杀。

/**
 * 线程池
 * 容量为1的线程池。 顺序执行。
 */
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Test_06_SingleThreadExecutor {

    public static void main(String[] args) {
        ExecutorService service = Executors.newSingleThreadExecutor();
        System.out.println(service);

        for (int i = 0; i < 5; i++) {
            service.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        TimeUnit.MILLISECONDS.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + " - test executor");
                }
            });
        }

    }
}

  运行结果:

java.util.concurrent.Executors$FinalizableDelegatedExecutorService@483bf400
pool-1-thread-1 - test executor
pool-1-thread-1 - test executor
pool-1-thread-1 - test executor
pool-1-thread-1 - test executor
pool-1-thread-1 - test executor

  注意:SingleThreadExceutor实现是基于LinkedBlockingQueue的。

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

10、ForkJoinPool

  分支合并线程池(mapduce 类似的设计思想)。适合用于处理复杂任务。 初始化线程容量与 CPU 核心数相关。
  线程池中运行的内容必须是 ForkJoinTask 的子类型(RecursiveTask,RecursiveAction)。 ForkJoinPool - 分支合并线程池。 可以递归完成复杂任务。要求可分支合并的任务必须是 ForkJoinTask 类型的子类型。其中提供了分支和合并的能力。ForkJoinTask 类型提供了两个抽象子类型,RecursiveTask 有返回结果的分支合并任务,RecursiveAction无返回结果的分支合并任务。(Callable/Runnable)compute 方法:就是任务的执行逻辑。

  ForkJoinPool 没有所谓的容量。默认都是 1 个线程。根据任务自动的分支新的子线程。 当子线程任务结束后,自动合并。所谓自动是根据 fork 和 join 两个方法实现的。

  应用: 主要是做科学计算或天文计算的。数据分析的。

/**
 * 线程池
 * 分支合并线程池。
 */
import java.io.IOException;
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 Test_08_ForkJoinPool {

    final static int[] numbers = new int[1000000];
    final static int MAX_SIZE = 50000;
    final static Random r = new Random();


    static {
        for (int i = 0; i < numbers.length; i++) {
            numbers[i] = r.nextInt(1000);
        }
    }

    public static void main(String[] args) throws InterruptedException, ExecutionException, IOException {
        long result = 0L;
        for (int i = 0; i < numbers.length; i++) {
            result += numbers[i];
        }
        System.out.println(result);

        ForkJoinPool pool = new ForkJoinPool();
        AddTask task = new AddTask(0, numbers.length);

        Future<Long> future = pool.submit(task);
        System.out.println(future.get());

    }

    static class AddTask extends RecursiveTask<Long> { // RecursiveAction
        int begin, end;

        public AddTask(int begin, int end) {
            this.begin = begin;
            this.end = end;
        }

        //
        protected Long compute() {
            if ((end - begin) < MAX_SIZE) {
                long sum = 0L;
                for (int i = begin; i < end; i++) {
                    sum += numbers[i];
                }
                // System.out.println("form " + begin + " to " + end + " sum is : " + sum);
                return sum;
            } else {
                int middle = begin + (end - begin) / 2;
                AddTask task1 = new AddTask(begin, middle);
                AddTask task2 = new AddTask(middle, end);
                task1.fork();// fork - 就是用于开启新的任务的。 就是分支工作的。 就是开启一个新的线程任务。
                task2.fork();
                // join - 合并。将任务的结果获取。 这是一个阻塞方法。一定会得到结果数据。
                return task1.join() + task2.join();
            }
        }
    }
}

11、WorkStealingPool

  JDK1.8 新增的线程池。工作窃取线程池。当线程池中有空闲连接时,自动到等待队列中 窃取未完成任务,自动执行。

  初始化线程容量与 CPU 核心数相关。此线程池中维护的是精灵线程。 ExecutorService.newWorkStealingPool ();

12、ThreadPoolExecutor

  线程池底层实现。除 ForkJoinPool 外,其他常用线程池底层都是使用 ThreadPoolExecutor实现的。

public ThreadPoolExecutor
  (int corePoolSize, // 核心容量,创建线程池的时候,默认有多少线程。也是线程池保持的最少线程数。
  int maximumPoolSize, // 最大容量,线程池最多有多少线程
  long keepAliveTime, // 生命周期,0为永久。当线程空闲多久后,自动回收。
  TimeUnit unit, // 生命周期单位,为生命周期提供单位,如:秒,毫秒
  BlockingQueue<Runnable> workQueue // 任务队列,阻塞队列。 注意:泛型必须是 Runnable
);

  使用场景: 默认提供的线程池不满足条件时使用。如:初始线程数据 4,最大线程数 200,线程空闲周期 30 秒。

/**
 * 线程池
 * 模拟固定容量线程池
 */
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Test_09_ThreadPoolExecutor {

    public static void main(String[] args) {
        // 模拟fixedThreadPool, 核心线程5个,最大容量5个,线程的生命周期无限。
        ExecutorService service =
                new ThreadPoolExecutor(5, 5, 0L, TimeUnit.MILLISECONDS,
                        new LinkedBlockingQueue<Runnable>());

        for (int i = 0; i < 6; i++) {
            service.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        TimeUnit.MILLISECONDS.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + " - test executor");
                }
            });
        }

        System.out.println(service);

        service.shutdown();
        System.out.println(service.isTerminated());
        System.out.println(service.isShutdown());
        System.out.println(service);

        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        service.shutdown();
        System.out.println(service.isTerminated());
        System.out.println(service.isShutdown());
        System.out.println(service);

    }
}

  运行结果:

java.util.concurrent.ThreadPoolExecutor@71f2a7d5[Running, pool size = 5, active threads = 5, queued tasks = 1, completed tasks = 0]
false
true
java.util.concurrent.ThreadPoolExecutor@71f2a7d5[Shutting down, pool size = 5, active threads = 5, queued tasks = 1, completed tasks = 0]
pool-1-thread-2 - test executor
pool-1-thread-1 - test executor
pool-1-thread-5 - test executor
pool-1-thread-3 - test executor
pool-1-thread-4 - test executor
pool-1-thread-2 - test executor
true
true
java.util.concurrent.ThreadPoolExecutor@71f2a7d5[Terminated, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 6]

13、性能问题

  如下示例为线程池和单线程运算时的性能测试。

/**
 * 线程池
 * 固定容量线程池, 简单应用
 */
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class Test_04_ParallelComputingWithFixedThreadPool {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        long start = System.currentTimeMillis();
        computing(1, 200000);
        long end = System.currentTimeMillis();
        System.out.println("computing times : " + (end - start));

        ExecutorService service = Executors.newFixedThreadPool(5);

        ComputingTask t1 = new ComputingTask(1, 60000);
        ComputingTask t2 = new ComputingTask(60001, 110000);
        ComputingTask t3 = new ComputingTask(110001, 150000);
        ComputingTask t4 = new ComputingTask(150001, 180000);
        ComputingTask t5 = new ComputingTask(180001, 200000);

        Future<List<Integer>> f1 = service.submit(t1);
        Future<List<Integer>> f2 = service.submit(t2);
        Future<List<Integer>> f3 = service.submit(t3);
        Future<List<Integer>> f4 = service.submit(t4);
        Future<List<Integer>> f5 = service.submit(t5);

        start = System.currentTimeMillis();
        f1.get();
        f2.get();
        f3.get();
        f4.get();
        f5.get();
        end = System.currentTimeMillis();
        System.out.println("parallel computing times : " + (end - start));

    }

    private static List<Integer> computing(Integer start, Integer end) {
        List<Integer> results = new ArrayList<>();
        boolean isPrime = true;
        for (int i = start; i <= end; i++) {
            for (int j = 1; j < Math.sqrt(i); j++) {
                if (i % j == 0) {
                    isPrime = false;
                    break;
                }
            }
            if (isPrime) {
                results.add(i);
            }
            isPrime = true;
        }

        return results;
    }

    static class ComputingTask implements Callable<List<Integer>> {
        int start, end;

        public ComputingTask(int start, int end) {
            this.start = start;
            this.end = end;
        }

        public List<Integer> call() throws Exception {
            List<Integer> results = new ArrayList<>();
            boolean isPrime = true;
            for (int i = start; i <= end; i++) {
                for (int j = 1; j < Math.sqrt(i); j++) {
                    if (i % j == 0) {
                        isPrime = false;
                        break;
                    }
                }
                if (isPrime) {
                    results.add(i);
                }
                isPrime = true;
            }

            return results;
        }
    }
}

  运行结果:

computing times : 9
parallel computing times : 1

猜你喜欢

转载自www.cnblogs.com/jing99/p/10817449.html