0
点赞
收藏
分享

微信扫一扫

Java CountDownLatch和Semaphore

SDKB英文 2022-03-23 阅读 81
java

1. 怎么理解CountDownLatch?【内部也是AQS】

参照如上:线程1调用await阻塞。直到调用若干次的countDown后(具体次数,初始化的时候已经指定),才会唤醒继续

2. 如果多个线程前置调用await呢?

public class CountDownLatchDemo {

    static CountDownLatch countDownLatch = new CountDownLatch(2);

    public static void main(String[] args) {

        new Thread(()->{
            try {
                countDownLatch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("t4");
        }, "t4").start();

        new Thread(()->{
            try {
                countDownLatch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("t5");
        }, "t5").start();

        new Thread(()->{
            try {
                countDownLatch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("t1");
        }, "t1").start();
        new Thread(()->{
            countDownLatch.countDown();
            System.out.println("t2");
        }, "t2").start();
        new Thread(()->{
            countDownLatch.countDown();
            System.out.println("t3");
        }, "t3").start();

    }
}

3. 如何理解Semaphore呢?【AQS相关-队列】

4. 理解SemaphoreDemo

public class SemaphoreDemo {

    static Semaphore semaphore = new Semaphore(2);
    public static void main(String[] args) throws InterruptedException {
        new Thread(() -> {
            try {
                semaphore.acquire();
                System.out.println(Thread.currentThread().getName());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        },"t1").start();
        new Thread(() -> {
            try {
                semaphore.acquire();
                System.out.println(Thread.currentThread().getName());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        },"t2").start();
        new Thread(() -> {
            try {
                semaphore.acquire();
                System.out.println(Thread.currentThread().getName());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        },"t3").start();
        new Thread(() -> {
            try {
                semaphore.acquire();
                System.out.println(Thread.currentThread().getName());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        },"t4").start();

        Thread.sleep(1000);
        semaphore.release();
    }
}

 

 

举报

相关推荐

0 条评论