线程同步的辅助类

一:CountDownLatch

是java.util.cucurrent下的一个类,这个类可以实现线程的同步阻塞。

通过一个计数器来实现,计数器的初始值是可以设置成线程的数量。每当一个线程执行完毕后,计数器的值就-1,当计数器的值为0时,表示所有线程都执行完毕,然后在闭锁上等待的线程就可以恢复工作了。

leetCode:

https://leetcode-cn.com/problems/print-in-order/

二:Semaphore

也是一个线程同步的辅助类,可以维护当前访问自身的线程个数,并提供了同步机制。使用Semaphore可以控制同时访问资源的线程个数,例如,实现一个文件允许的并发访问数。

Semaphore的主要方法摘要:

  void acquire():从此信号量获取一个许可,在提供一个许可前一直将线程阻塞,否则线程被中断。

  void release():释放一个许可,将其返回给信号量。

  int availablePermits():返回此信号量中当前可用的许可数。

扫描二维码关注公众号,回复: 12347530 查看本文章

  boolean hasQueuedThreads():查询是否有线程正在等待获取

leetCode:

https://leetcode-cn.com/problems/print-foobar-alternately/submissions/

使用CountDownLatch也可以解决,只是时间太长没有通过

class FooBar {
    private int n;
    private CountDownLatch cdl;
    private CountDownLatch cdl2;

    public FooBar(int n) {
        this.n = n;
        cdl = new CountDownLatch(1);
        cdl2 = new CountDownLatch(0);
    }
    
    public void foo(Runnable printFoo) throws InterruptedException {
        
        for (int i = 0; i < n; i++) {
            
        	// printFoo.run() outputs "foo". Do not change or remove this line.
            cdl2.await();
        	printFoo.run();
            cdl.countDown();
            cdl2 = new CountDownLatch(1);
        }
    }

    public void bar(Runnable printBar) throws InterruptedException {
        
        for (int i = 0; i < n; i++) { 
            // printBar.run() outputs "bar". Do not change or remove this line.
            cdl.await();
        	printBar.run();
            cdl2.countDown();
            cdl = new CountDownLatch(1);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/CarryBest/article/details/112767369