CountDownLatch

干饭达人GoodLucy發表於2024-08-15
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());
    }

}

相關文章