java中的CountDownLatch(共享锁)与ReentrantLock(排他锁)

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_43313769/article/details/86682532

CountDownLatch(共享锁)又叫门闩。生成的时候需要说明门闩的数量,等到门闩的个数减为零的时候等待的线程可以启动。
来看一段代码
注意这里等待调用await()方法

public class TestDemo {
    public static void main(String[] args) {
       CountDownLatch latch = new CountDownLatch(5);
        new Thread(()->{
            System.out.println("t1启动");
            try {
                latch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("\nt1停止");
        }).start();

        new Thread(()->{
            for(int i = 0;i<10;i++) {
                System.out.print(latch.getCount()+"\t");
                   latch.countDown();
                try {
                    TimeUnit.MILLISECONDS.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}

运行结果:
t1启动
5 4 3 2 1
t1停止
0 0 0 0 0

排他锁又叫可重入锁,可以使Condition对象进行await并通过signal唤醒。同样实现这段逻辑

public class Test3 {
    public static void main(String[] args) {
        Lock lock0 = new ReentrantLock(true);//公平锁
        Lock lock1 = new ReentrantLock(false);//非公平锁
       Condition condition = lock0.newCondition();
        new Thread(()->{
            System.out.println("t1启动");
            try {
                lock0.lock();
                condition.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            lock0.unlock();
            System.out.println("\nt1停止");
        },"t1").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    if (i == 5) {
                        lock0.lock();
                        condition.signal();
                        lock0.unlock();
                    }
                    TimeUnit.MILLISECONDS.sleep(100);
                    System.out.print(i+"\t");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "t2").start();
    }
}
展开阅读全文

没有更多推荐了,返回首页