CountDownLatch

import lombok.SneakyThrows;

import java.util.Date;
import java.util.concurrent.*;

/*
main上锁3
线程1获得锁
线程2获得锁
线程3获得锁
线程1释放锁2
线程2释放锁1
线程3释放锁0
main解锁0
 * */
public class T {

    @SneakyThrows
    public static void main(String[] args) {
        CountDownLatch latch = new CountDownLatch(3);

        System.out.println(Thread.currentThread().getName() + "上锁" + latch.getCount());

        new Thread(() -> {
            try {
                System.out.println(Thread.currentThread().getName() + "获得锁");
                Thread.sleep(200);
                latch.countDown();
                System.out.println(Thread.currentThread().getName() + "释放锁" + latch.getCount());
            } catch (Exception e) {

            }
        }, "线程1").start();

        new Thread(() -> {
            try {
                System.out.println(Thread.currentThread().getName() + "获得锁");
                Thread.sleep(500);
                latch.countDown();
                System.out.println(Thread.currentThread().getName() + "释放锁" + latch.getCount());
            } catch (Exception e) {

            }
        }, "线程2").start();

        new Thread(() -> {
            try {
                System.out.println(Thread.currentThread().getName() + "获得锁");
                Thread.sleep(1000);
                latch.countDown();
                System.out.println(Thread.currentThread().getName() + "释放锁" + latch.getCount());
            } catch (Exception e) {

            }
        }, "线程3").start();

        latch.await();
        System.out.println(Thread.currentThread().getName() + "解锁" + latch.getCount());
    }

}
posted @ 2024-08-15 15:35  干饭达人GoodLucy  阅读(4)  评论(0编辑  收藏  举报