Java并发辅助类CountDownLatch、CyclicBarrier和 Semaphore

Java并发辅助类CountDownLatch、CyclicBarrier和 Semaphore

概述

马老师多线程视频学习总结(好记性不如烂笔头)。

CountDownLatch用法

CountDownLatch类位于java.util.concurrent包下,利用它可以实现类似计数器的功能。比如有一个任务A,它要等待其他4个任务执行完毕之后才能执行,此时就可以利用CountDownLatch来实现这种功能了。

CountDownLatch类只提供了一个构造器:

    // 参数count为计数器
    public CountDownLatch(int count) {
        if (count < 0) throw new IllegalArgumentException("count < 0");
        this.sync = new Sync(count);
    }

CountDownLatch类有3个重要的方法:

    // 调用await()方法的线程会被挂起,它会等待直到count值为0才继续执行
    public void await() throws InterruptedException {
        sync.acquireSharedInterruptibly(1);
    }
    // 和await()类似,只不过等待一定的时间后count值还没变为0的话就会继续执行
    public boolean await(long timeout, TimeUnit unit)
        throws InterruptedException {
        return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
    }
    // //将count值减1
    public void countDown() {
        sync.releaseShared(1);
    }

使用CountDownLatch:

package com.wz.code.test.thread;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

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

        new Thread(()->{
            System.out.println("子线程" + Thread.currentThread().getName() + "开始执行");
            try {
                TimeUnit.MILLISECONDS.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("子线程" + Thread.currentThread().getName() + "执行完成");
            latch.countDown();
        }, "t1").start();

        new Thread(()->{
            System.out.println("子线程" + Thread.currentThread().getName() + "开始执行");
            try {
                TimeUnit.MILLISECONDS.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("子线程" + Thread.currentThread().getName() + "执行完成");
            latch.countDown();
        }, "t2").start();

        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("两个子线程执行完了");
        System.out.println("主线程" + Thread.currentThread().getName() + "开始执行");
    }
}

在这里插入图片描述

CyclicBarrier用法

CyclicBarrier字面意思回环栅栏,通过它可以实现让一组线程等待至某个状态之后再全部同时执行。叫做回环是因为当所有等待线程都被释放以后,CyclicBarrier可以被重用。我们暂且把这个状态就叫做barrier,当调用await()方法之后,线程就处于barrier了。
CyclicBarrier类位于java.util.concurrent包下,CyclicBarrier提供2个构造器:

    public CyclicBarrier(int parties, Runnable barrierAction) {
        if (parties <= 0) throw new IllegalArgumentException();
        this.parties = parties;
        this.count = parties;
        this.barrierCommand = barrierAction;
    }
    public CyclicBarrier(int parties) {
        this(parties, null);
    }

参数parties指让多少个线程或者任务等待至barrier状态;参数barrierAction为当这些线程都达到barrier状态时会执行的内容。

CyclicBarrier中最重要的方法就是await方法,它有2个重载版本:

    public int await() throws InterruptedException, BrokenBarrierException {
        try {
            return dowait(false, 0L);
        } catch (TimeoutException toe) {
            throw new Error(toe); // cannot happen
        }
    }
    public int await(long timeout, TimeUnit unit)
        throws InterruptedException,
               BrokenBarrierException,
               TimeoutException {
        return dowait(true, unit.toNanos(timeout));
    }

第一个版本比较常用,用来挂起当前线程,直至所有线程都到达barrier状态再同时执行后续任务;
第二个版本是让这些线程等待至一定的时间,如果还有线程没有到达barrier状态就直接让到达barrier的线程执行后续任务。

假若有若干个线程都要进行写数据操作,并且只有所有线程都完成写数据操作之后,这些线程才能继续做后面的事情,此时就可以利用CyclicBarrier了:

package com.wz.code.test.thread;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;

public class CyclicBarrierTest {
    public static void main(String[] args) {
        final int NUM = 4;
        CyclicBarrier barrier = new CyclicBarrier(NUM);
        for (int i = 0; i < NUM; i++)
            new MyThread(barrier).start();
    }

    static class MyThread extends Thread {
        private CyclicBarrier barrier;
        public MyThread(CyclicBarrier barrier) {
            this.barrier = barrier;
        }

        @Override
        public void run() {
            System.out.println("线程" + Thread.currentThread().getName() + "正在写入数据");
            try {
                TimeUnit.MILLISECONDS.sleep(5000);
                System.out.println("线程" + Thread.currentThread().getName() + "写入数据完毕");
                barrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
            System.out.println("所有线程写入完毕, 继续处理其他任务...");
        }
    }
}

程序执行结果:
在这里插入图片描述
从上面输出结果可以看出,每个写入线程执行完写数据操作之后,就在等待其他线程写入操作完毕。

当所有线程线程写入操作完毕之后,所有线程就继续进行后续的操作了。

如果说想在所有线程写入操作完之后,进行额外的其他操作可以为CyclicBarrier提供Runnable参数:

package com.wz.code.test.thread;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;

public class CyclicBarrierTest2 {
    public static void main(String[] args) {
        final int NUM = 4;
        CyclicBarrier barrier = new CyclicBarrier(NUM, new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "新的任务开始了...");
                try {
                    TimeUnit.MILLISECONDS.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("新的任务结束了...");
            }
        });
        for (int i = 0; i < NUM; i++)
            new MyThread(barrier).start();
    }

    static class MyThread extends Thread {
        private CyclicBarrier barrier;
        public MyThread(CyclicBarrier barrier) {
            this.barrier = barrier;
        }

        @Override
        public void run() {
            System.out.println("线程" + Thread.currentThread().getName() + "正在写入数据");
            try {
                TimeUnit.MILLISECONDS.sleep(5000);
                System.out.println("线程" + Thread.currentThread().getName() + "写入数据完毕");
                barrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
            System.out.println("所有线程写入完毕, 继续处理其他任务...");
        }
    }
}

程序执行结果:
在这里插入图片描述
从结果可以看出,当四个线程都到达barrier状态后,会从四个线程中选择一个线程去执行Runnable。

下面看一下为await指定时间的效果:

package com.wz.code.test.thread;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CyclicBarrierTest3 {
    public static void main(String[] args) {
        final int NUM = 4;
        CyclicBarrier barrier = new CyclicBarrier(NUM);
        for (int i = 0; i < NUM; i++) {
            if (i < NUM- 1) {
                new MyThread(barrier).start();
            } else {
                try {
                    TimeUnit.MILLISECONDS.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                new MyThread(barrier).start();
            }
        }
    }

    static class MyThread extends Thread {
        private CyclicBarrier barrier;
        public MyThread(CyclicBarrier barrier) {
            this.barrier = barrier;
        }

        @Override
        public void run() {
            System.out.println("线程" + Thread.currentThread().getName() + "正在写入数据");
            try {
                TimeUnit.MILLISECONDS.sleep(5000);
                System.out.println("线程" + Thread.currentThread().getName() + "写入数据完毕");
                barrier.await(2000, TimeUnit.MILLISECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            } catch (TimeoutException e) {
                e.printStackTrace();
            }
            System.out.println("所有线程写入完毕, 继续处理其他任务...");
        }
    }
}

程序执行结果:
在这里插入图片描述
上面的代码在main方法的for循环中,故意让最后一个线程启动延迟,因为在前面三个线程都达到barrier之后,等待了指定的时间发现第四个线程还没有达到barrier,就抛出异常并继续执行后面的任务。

另外CyclicBarrier是可以重用的,看下面这个例子:

package com.wz.code.test.thread;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;

public class CyclicBarrierTest4 {
    public static void main(String[] args) {
        final int NUM = 4;
        CyclicBarrier barrier = new CyclicBarrier(NUM);
        for (int i = 0; i < NUM; i++)
            new MyThread(barrier).start();

        try {
            Thread.sleep(25000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("=======CyclicBarrier重用========");

        for (int i = 0; i < NUM; i++)
            new MyThread(barrier).start();
    }

    static class MyThread extends Thread {
        private CyclicBarrier barrier;
        public MyThread(CyclicBarrier barrier) {
            this.barrier = barrier;
        }

        @Override
        public void run() {
            System.out.println("线程" + Thread.currentThread().getName() + "正在写入数据");
            try {
                TimeUnit.MILLISECONDS.sleep(5000);
                System.out.println("线程" + Thread.currentThread().getName() + "写入数据完毕");
                barrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
            System.out.println("所有线程写入完毕, 继续处理其他任务...");
        }
    }
}

程序执行结果:
在这里插入图片描述
从执行结果可以看出,在初次的4个线程越过barrier状态后,又可以用来进行新一轮的使用。而CountDownLatch无法进行重复使用。

Semaphore用法

Semaphore翻译成字面意思为 信号量,Semaphore可以控同时访问的线程个数,通过 acquire() 获取一个许可,如果没有就等待,而 release() 释放一个许可。

Semaphore类位于java.util.concurrent包下,它提供了2个构造器:

    // 参数permits表示许可数目,即同时可以允许多少线程进行访问
    public Semaphore(int permits) {
        sync = new NonfairSync(permits);
    }
    // 这个多了一个参数fair表示是否是公平的,即等待时间越久的越先获取许可
    public Semaphore(int permits, boolean fair) {
        sync = fair ? new FairSync(permits) : new NonfairSync(permits);
    }

下面说一下Semaphore类中比较重要的几个方法,首先是acquire()、release()方法:

    // 获取一个许可
    public void acquire() throws InterruptedException {
        sync.acquireSharedInterruptibly(1);
    }
    // 获取permits个许可
    public void acquire(int permits) throws InterruptedException {
        if (permits < 0) throw new IllegalArgumentException();
        sync.acquireSharedInterruptibly(permits);
    }
	// 释放一个许可
    public void release() {
        sync.releaseShared(1);
    }
    // 释放permits个许可
    public void release(int permits) {
        if (permits < 0) throw new IllegalArgumentException();
        sync.releaseShared(permits);
    }

acquire()用来获取一个许可,若无许可能够获得,则会一直等待,直到获得许可。

release()用来释放许可。注意,在释放许可之前,必须先获获得许可。

这4个方法都会被阻塞,如果想立即得到执行结果,可以使用下面几个方法:

    // 尝试获取一个许可,若获取成功,则立即返回true,若获取失败,则立即返回false
    public boolean tryAcquire() {
        return sync.nonfairTryAcquireShared(1) >= 0;
    }
    // 尝试获取一个许可,若在指定的时间内获取成功,则立即返回true,否则则立即返回false
    public boolean tryAcquire(long timeout, TimeUnit unit)
        throws InterruptedException {
        return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
    }
    // 尝试获取permits个许可,若获取成功,则立即返回true,若获取失败,则立即返回false
    public boolean tryAcquire(int permits) {
        if (permits < 0) throw new IllegalArgumentException();
        return sync.nonfairTryAcquireShared(permits) >= 0;
    }
    // 尝试获取permits个许可,若在指定的时间内获取成功,则立即返回true,否则则立即返回false
    public boolean tryAcquire(int permits, long timeout, TimeUnit unit)
        throws InterruptedException {
        if (permits < 0) throw new IllegalArgumentException();
        return sync.tryAcquireSharedNanos(permits, unit.toNanos(timeout));
    }

可以通过availablePermits()方法得到可用的许可数目:

    public int availablePermits() {
        return sync.getPermits();
    }

下面通过一个例子来看一下Semaphore的具体使用:

假若一个工厂有5台机器,但是有8个工人,一台机器同时只能被一个工人使用,只有使用完了,其他工人才能继续使用。那么我们就可以通过Semaphore来实现:

package com.wz.code.test.thread;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoreTest {

    public static void main(String[] args) {
        // 工人数量
        final int W_NUM = 8;
        // 机器数量
        final int M_NUM = 5;
        Semaphore semaphore = new Semaphore(M_NUM);

        for (int i = 0; i < W_NUM; i++)
            new Thread(new Worker(i, semaphore)).start();
    }

    static class Worker implements Runnable {
        private int num;
        private Semaphore semaphore;
        public Worker(int num, Semaphore semaphore) {
            this.num = num;
            this.semaphore = semaphore;
        }

        @Override
        public void run() {
            try {
                semaphore.acquire();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("工人" + num + "占用一个机器在生产...");
            try {
                TimeUnit.MILLISECONDS.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            semaphore.release();
            System.out.println("工人" + num + "释放一个机器...");
        }
    }
}

在这里插入图片描述

总结

下面对上面说的三个辅助类进行一个总结:

  • CountDownLatch和CyclicBarrier都能够实现线程之间的等待,只不过它们侧重点不同:
  1. CountDownLatch一般用于某个线程A等待若干个其他线程执行完任务之后,它才执行;
  2. 而CyclicBarrier一般用于一组线程互相等待至某个状态,然后这一组线程再同时执行;
  3. 另外,CountDownLatch是不能够重用的,而CyclicBarrier是可以重用的。
  • Semaphore其实和锁有点类似,它一般用于控制对某组资源的访问权限。

参考博客:http://www.importnew.com/21889.html

猜你喜欢

转载自blog.csdn.net/wz122330/article/details/88311738
今日推荐