Administrator
发布于 2024-08-07 / 20 阅读
0
0

利用notify 和wait方法实现CountDownLatch

CountDownLatch 是 Java 中的一个同步辅助工具,用于让一个或多个线程等待一组事件发生。以下是使用 waitnotify 方法实现一个自定义的 CountDownLatch 的示例:

public class MyCountDownLatch {
    private int count;
    private final Object lock = new Object();

    public MyCountDownLatch(int count) {
        if (count < 0) {
            throw new IllegalArgumentException("Count cannot be negative");
        }
        this.count = count;
    }

    // 减少计数,如果计数到达0,则唤醒所有等待的线程
    public synchronized void countDown() {
        count--;
        if (count == 0) {
            notifyAll();
        }
    }

    // 等待计数到达0,如果当前计数大于0,则调用wait方法等待
    public synchronized void await() throws InterruptedException {
        while (count > 0) {
            wait();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        final MyCountDownLatch latch = new MyCountDownLatch(3);

        // 创建并启动三个线程,每个线程执行完毕后都会调用countDown方法
        for (int i = 0; i < 3; i++) {
            int finalI = i;
            new Thread(() -> {
                try {
                    System.out.println("Thread " + finalI + " is doing some work.");
                    // 模拟工作耗时
                    Thread.sleep((int) (Math.random() * 1000));
                    System.out.println("Thread " + finalI + " finished work, counting down latch.");
                    latch.countDown();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }).start();
        }

        // 主线程等待所有线程完成工作
        System.out.println("Main thread is waiting for all threads to complete their work.");
        latch.await();
        System.out.println("All threads have completed their work. Continuing main thread.");
    }
}

在这个示例中,MyCountDownLatch 类使用一个整数 count 来跟踪需要等待的事件数量。构造函数接收一个整数参数,初始化 count 的值。

countDown 方法用于减少 count 的值。每当调用这个方法时,count 就会减1。如果 count 变为0,表示所有事件都已发生,此时通过调用 notifyAll 方法唤醒所有等待的线程。

await 方法用于线程等待直到 count 变为0。如果 count 大于0,调用 wait 方法使当前线程等待,直到 count 变为0或被中断。

main 方法中,我们创建了一个 MyCountDownLatch 实例,并设置了计数为3。然后,我们启动了三个线程,每个线程执行一些工作,然后调用 countDown 方法。主线程调用 await 方法等待所有三个线程完成工作。

请注意,这个自定义的 CountDownLatch 实现是简化的,并没有处理像 tryAcquiretryRelease 这样的超时机制,也没有提供中断处理的高级选项。在实际应用中,你可能需要添加更多的功能来满足特定的需求。


评论