多线程基础学习

2019-04-27 java常用线程池

2019-04-27  本文已影响0人  zecan

1. 为什么要使用线程池

在上一节中已经介绍了线程的创建方式,当需要并行执行一个任务就创建一个线程来执行。但是频繁的创建线程以及回收线程资源,容易在jvm中造成很大的性能消耗。这时我们就会想:能不能在一个池子中创建线程,当有任务来时,就从池子中取出一个线程来执行任务,当任务执行完毕,就将线程放回池子里面,等待下一个需要执行的任务。上帝说要有池子,于是便有了线程池。

2.线程池的创建以及常用的线程池

//常见的线程池创建都是通过调用Executors的静态方法生成
ExecutorService pool = Executors.newCachedThreadPool();
//看下Executors的内部静态创建线程池方法
  public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }
//再看下ThreadPoolExcutor的构造函数,初步了解下各个参数的意义,下一节会有详解
 public ThreadPoolExecutor(int corePoolSize,  int maximumPoolSize,
              long keepAliveTime,TimeUnit unit,  BlockingQueue<Runnable> workQueue) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             Executors.defaultThreadFactory(), defaultHandler);                                    

如上面所示,我们最常使用的cachedThreadPool就是通过调用Executors的静态方法生成,它是一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。具有以下特点:

除了CachedThreadPool,还有以下几种常见的线程池

(1)FixedThreadPool

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

FixedThreadPool创建一个指定工作线程数量的线程池。每当提交一个任务就创建一个工作线程,如果工作线程数量达到线程池初始的最大数,则将提交的任务存入到池队列LinkedBlockingQueue中。

FixedThreadPool是一个典型且优秀的线程池,它具有线程池提高程序效率和节省创建线程时所耗的开销的优点。但是,在线程池空闲时,即线程池中没有可运行任务时,它不会释放工作线程,还会占用一定的系统资源。

(2)SingleThreadExecutor

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

SingleThreadExecutor创建一个单线程化的Executor,即只创建唯一的工作者线程来执行任务,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。如果这个线程异常结束,会有另一个取代它,保证顺序执行。
单工作线程最大的特点是可保证顺序地执行各个任务,并且在任意给定的时间不会有多个线程是活动的。

(3)ScheduledThreadPool

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
        return new ScheduledThreadPoolExecutor(corePoolSize);
    }
  public ScheduledThreadPoolExecutor(int corePoolSize) {
        super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
              new DelayedWorkQueue());
    }

ScheduledThreadPool创建一个定长的线程池,而且支持定时的以及周期性的任务执行,支持定时及周期性任务执行。

3.使用例子

CacheThreadPool、FixedThreadPool、SingleThreadExecutor用法都是差不多的,都是将一个任务直接交给线程池execute,最终得到结果。

package com.demo.noteBook;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
public class CacheThreadPoolTest {
    public static void main(String[] args) throws Exception {
        ExecutorService cacheThreadPool = Executors.newCachedThreadPool();
        //这里如果用volatile修饰int保存结果,由于累加和赋值不是原子操作,会导致结果出错
        AtomicInteger sumResult = new AtomicInteger(0);
        for(int k = 0; k < 10; k++){
            cacheThreadPool.execute(()->{
                for(int i = 1; i <= 100; i++){
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    sumResult.addAndGet(i);
                    System.out.println("sumResult is" + sumResult) ;
                }
            });
        }
        //将线程池关闭,不再接受新任务,等待线程池里面的任务执行完成
        cacheThreadPool.shutdown();
        //在调用shutdown后,才会在任务都执行完毕后,将isTerminated设置为true
        while(true){
            if(cacheThreadPool.isTerminated()){
                System.out.println("sumResult is over" + sumResult) ;
                break;
            }
        }
    }
}

ScheduleThreadPool使用方法比较特殊,首先它不是使用ExecutorService,而是它的子类ScheduledExecutorService,它按周期执行任务的方法不是execute,而是ScheduledExecutorService的schedule等方法,下面是一个使用的例子:

package com.demo.noteBook;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class ScheduleThreadPoolTest {
    public static void main(String[] args) {
        //实现功能,在程序运行5s后,每隔3s say hello 一次
        ScheduledExecutorService scheduleThreadPo =
                          Executors.newScheduledThreadPool(5);
        scheduleThreadPool.scheduleAtFixedRate(new Runnable(){
            public void run(){
                System.out.println(" I say hello");
            }
        }, 5, 3, TimeUnit.SECONDS);
    }
}

参考文章:
https://www.cnblogs.com/aaron911/p/6213808.html

上一篇 下一篇

猜你喜欢

热点阅读