Java线程池的实现与应用

线程池所涉及的基本应用场景:

 

图 转自:https://juejin.im/entry/59aeaafd51882538cb1ec2f8

从这个应用场景中,基本会涉及到:

  • 线程、线程池相关的接口、类和方法
  • 相关的数据结构---> 主要是同步的数据结构,例如linkedBlockingQueue|ConcurrentLinkedQueue等

Java 多线程相关的接口、类继承关系:

 

说明:

  • Executor 执行器接口,该接口定义执行Runnable任务的方式。
  • ExecutorService 该接口定义提供对Executor的服务。
  • ScheduledExecutorService 定时调度接口。
  • AbstractExecutorService 执行框架抽象类。
  • ThreadPoolExecutor JDK中线程池的具体实现。
  • Executors 线程池工厂类。------>工厂设计模式

 

ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(() -> {
    String threadName = Thread.currentThread().getName();
    System.out.println("Hello " + threadName);
});

Callable<Integer> task = () -> {
    try {
        TimeUnit.SECONDS.sleep(1);
        return 123;
    }
    catch (InterruptedException e) {
        throw new IllegalStateException("task interrupted", e);
    }
};
ExecutorService executor = Executors.newFixedThreadPool(1);
Future<Integer> future = executor.submit(task);

System.out.println("future done? " + future.isDone());

Integer result = future.get();

System.out.println("future done? " + future.isDone());
System.out.print("result: " + result);

Spring 中的多线程处理方案:

在Spring中,通过任务执行器,也就是TaskExecutor来实现多线程和并发编程。使用ThreadPoolTaskExecutor可实现一个基于线程池的TaskExecutor。 

 

 

  •  构建线程池

     

  •  定义一个可运行的任务

    

  • 分配给线程池执行

     

与多线程相关的线程池:

 

 

 

真实案例:

North 52 SES中对于对线程方案的处理:

 

 

 

 

 

 

 

 

Reference:

Java 8 Concurrency Tutorial: Threads and Executors: http://winterbe.com/posts/2015/04/07/java8-concurrency-tutorial-thread-executor-examples/

Future 模式: https://openhome.cc/Gossip/DesignPattern/FuturePattern.htm

深度解读 java 线程池设计思想及源码实现: https://juejin.im/entry/59aeaafd51882538cb1ec2f8

posted @ 2017-11-29 22:15  chp008  阅读(338)  评论(0编辑  收藏  举报