CountDownLatch / CyclicBarrier / Semaphore

CountDownLatch 倒计时锁

 CyclicBarrier 循环栅栏

Semaphore 信号量

主要用于两个目的,一个是用于多个共享资源的互斥使用,另一个用于并发线程数的控制

线程顺序控制示例

实现三个线程A->B->C启动,要求如下:

AAA打印5次,BBB打印10次,CCC打印15次

然后继续:AAA打印5次,BBB打印10次,CCC打印15次

....循环10次

class ShareResource{
    private int flag = 1;
    private Lock lock = new ReentrantLock();
    private Condition c1 = lock.newCondition();
    private Condition c2 = lock.newCondition();
    private Condition c3 = lock.newCondition();

    public void print(int printCount, int threadFlag) {
        lock.lock();
        try {
            while (flag != threadFlag) {
                if (threadFlag == 1) { c1.await(); }
                else if (threadFlag == 2) { c2.await(); }
                else if (threadFlag == 3) { c3.await(); }
            }
            for (int i = 0; i < printCount; i++) {
                System.out.println(Thread.currentThread().getName()+":"+(i+1));
            }
            if (threadFlag == 1) {
                flag = 2;
                c2.signal();
            } else if (threadFlag == 2) {
                flag = 3;
                c3.signal();
            } else if (threadFlag == 3) {
                flag = 1;
                c1.signal();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
public class ThreadDemo {
    public static void main(String[] args) {
        ShareResource shareResource = new ShareResource();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                shareResource.print(5, 1);
            }
        }, "线程A").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                shareResource.print(10, 2);
            }
        }, "线程B").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                shareResource.print(15, 3);
            }
        }, "线程C").start();
    }
}
posted @ 2021-07-02 05:54  一柒微笑  阅读(42)  评论(0编辑  收藏  举报