欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode12-多线程之按序打印

程序员文章站 2022-05-05 15:16:44
...

题目如图:

LeetCode12-多线程之按序打印

第一种解法(信号量)

import java.util.concurrent.Semaphore;
class Foo {
    public Semaphore Semaphore_one=new Semaphore(0);
    public Semaphore Semaphore_two=new Semaphore(0);
    public Foo() {
        
    }

    public void first(Runnable printFirst) throws InterruptedException {
        
        // printFirst.run() outputs "first". Do not change or remove this line.
        printFirst.run();
        Semaphore_one.release();
    }

    public void second(Runnable printSecond) throws InterruptedException {
    	//阻塞
        Semaphore_one.acquire();
        // printSecond.run() outputs "second". Do not change or remove this line.
        printSecond.run();
        Semaphore_two.release();
    }

    public void third(Runnable printThird) throws InterruptedException {
        Semaphore_two.acquire();
        // printThird.run() outputs "third". Do not change or remove this line.
        printThird.run();
    }
}

countdownlatch

class Foo {
    private CountDownLatch c2;
    private CountDownLatch c3;
    public Foo() {
         c2 = new CountDownLatch(1);
         c3 = new CountDownLatch(1);
    }
    
    public void first(Runnable printFirst) throws InterruptedException {
        
        // printFirst.run() outputs "first". Do not change or remove this line.
        printFirst.run();
        c2.countDown();
    }

    public void second(Runnable printSecond) throws InterruptedException {
        c2.await();
        // printSecond.run() outputs "second". Do not change or remove this line.
        printSecond.run();
        c3.countDown();
    }

    public void third(Runnable printThird) throws InterruptedException {
        c3.await();
        // printThird.run() outputs "third". Do not change or remove this line.
        printThird.run();
    }
}

相关标签: 基础 LeetCode