Java 线程工具类

1. CountDownLatch

CountDownLatch首先定义任务次数,并调用await()方法等待任务完成。调用countDown()方法表明已经完成一项任务,当任务全部完成后,继续await()方法后的任务。

public class CountDownLatchThread extends Thread {

    CountDownLatch latch;

    public CountDownLatchThread(CountDownLatch latch) {
        this.latch = latch;
    }

    public void run() {
        try {
            System.out.println(currentThread().getName() + " start");
            Thread.sleep(1000);
            latch.countDown();
            System.out.println(currentThread().getName() + " end");
        } catch (InterruptedException e) {
        }
    }

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(2);

        for (int i = 0; i < 2; i++) {
            new CountDownLatchThread(latch).start();
        }

        System.out.println(Thread.currentThread().getName() + " start");
        latch.await();
        System.out.println(Thread.currentThread().getName() + " end");
    }

}

输出
在这里插入图片描述

2. CyclicBarrier

CyclicBarrier会等待指定线程的await()方法调用结束。如果指定了三个线程CyclicBarrier(3),但只有2个线程调用了await()方法,这两个线程将一直等待下去。

public class CyclicBarrierThread extends Thread {

    CyclicBarrier barrier;

    public CyclicBarrierThread(CyclicBarrier barrier) {
        this.barrier = barrier;
    }

    public void run() {
        try {
            System.out.println(currentThread().getName() + " start");
            Thread.sleep(1000);
            barrier.await();
            System.out.println(currentThread().getName() + " end");
        } catch (Exception e) {
        }
    }

    public static void main(String[] args) {
        CyclicBarrier barrier = new CyclicBarrier(3);
        for (int i = 0; i < 3; i++) {
            new CyclicBarrierThread(barrier).start();
        }
    }

}

输出
在这里插入图片描述

可以调用CyclicBarrier的另一个构造函数CyclicBarrier(int, Runnable),在await()方法后最先调用Runnable.run()方法。

public static void main(String[] args) {
    CyclicBarrier barrier = new CyclicBarrier(3, new Runnable() {			
        @Override
        public void run() {
            System.out.println("In Runnable");
        }
    });
    for (int i = 0; i < 3; i++) {
        new CyclicBarrierThread(barrier).start();
    }
}

输出
在这里插入图片描述

3. ThreadPoolExecutor线程池

线程池处理流程

  • 核心线程池里线程是否都在执行任务。如果不是,则创建一个新的工作线程来执行任务。
  • 线程池工作队列是否已满。如果工作队列没有满,则把新提交任务存储在这个这个工作队列。
  • 线程池的线程是否都处于工作状态。如果没有,创建一个新的工作线程来执行任务。
  • 饱和策略处理任务。

ThreadPoolExecutor构造函数

public ThreadPoolExecutor(int corePoolSize,
                      int maximumPoolSize,
                      long keepAliveTime,
                      TimeUnit unit,
                      BlockingQueue<Runnable> workQueue,
                      ThreadFactory threadFactory,
                      RejectedExecutionHandler handler)
  • corePoolSize(线程池基本大小),创建新的线程来执行任务,直到线程池中数量大于基本大小。

  • workQueue(任务队列),用来保存等待执行的阻塞队列。

    • ArrayBlockingQueue,基于数组结构的阻塞队列
    • LinkedBlockingQueue,基于链表结构的阻塞队列
    • SynchronousQueue,不存储元素的阻塞队列,每个插入操作必须等待另一个移除操作。
    • PriorityBlockingQueue,一个拥有优先级的阻塞队列。
  • maximumPoolSize(线程池最大数量),线程池允许创建的最大数量,如果队列已满,并且创建的线程小于最大线程数,则线程池创建新的线程执行任务。

  • keepAliveTime(线程活动保持时间),线程池空闲时,保持存活的时间。

  • TimeUnit(线程活动保持时间的单位),可选DAYS(天)、HOURS(小时)、MINUTES(分钟)、SECONDS(秒)等。

  • threadFactory,设置创建线程的工厂

    public interface ThreadFactory {
        Thread newThread(Runnable r);
    }
    
  • handler(饱和策略),当队列和线程池都满了,必须采取策略处理新提交任务

    • AbortPolicy,直接抛出异常。
    • CallerRunsPolicy,在调用者所在线程运行任务。
    • DiscardOldestPolicy,丢弃队列里最近的一个任务。
    • DiscardPolicy,不处理,丢弃掉。

向线程池提交任务

  • execute(Runnable command),提交后不需要返回值,无法判断任务是否执行成功。
  • submit(Runnable task),提交后需要返回值,并通过Futureget()方法获取返回值。

4. Executors框架

Executors框架生成线程池

  • FixedThreadPool,创建固定线程数的线程池

    public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                  0L, TimeUnit.MILLISECONDS,
                                  new LinkedBlockingQueue<Runnable>());
    }
    
    public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                  0L, TimeUnit.MILLISECONDS,
                                  new LinkedBlockingQueue<Runnable>(),
                                  threadFactory);
    }
    
  • SingleThreadExecutor,创建单个线程的线程池

    public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                0L, TimeUnit.MILLISECONDS,
                                new LinkedBlockingQueue<Runnable>()));
    }
    
    public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                0L, TimeUnit.MILLISECONDS,
                                new LinkedBlockingQueue<Runnable>(),
                                threadFactory));
    }
    
  • CachedThreadPool,大小无界的线程池,适用于执行很多的短期异步任务。

    public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                  60L, TimeUnit.SECONDS,
                                  new SynchronousQueue<Runnable>());
    }
    
    public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                  60L, TimeUnit.SECONDS,
                                  new SynchronousQueue<Runnable>(),
                                  threadFactory);
    }
    
  • ScheduledThreadPool,适合于多个后台线程执行周期任务

    public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
        return new ScheduledThreadPoolExecutor(corePoolSize);
    }
    
    public static ScheduledExecutorService newScheduledThreadPool(
            int corePoolSize, ThreadFactory threadFactory) {
        return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
    }
    
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值