LeetCode刷題之旅【多線程篇】簡單 - 1:按序打印

2019年11月15日

 

題目

注意:

儘管輸入中的數字似乎暗示了順序,但是我們並不保證線程在操作系統中的調度順序。

你看到的輸入格式主要是爲了確保測試的全面性。

 

解題1:CountDownLatch

class Foo {
	private   CountDownLatch countDownLatchTwo = new CountDownLatch(1);
	private   CountDownLatch countDownLatchThree = new CountDownLatch(1);
	
    public Foo() {
        
    }

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

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

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

解題2


class Foo {
    
    private boolean firstFinished;
    private boolean secondFinished;
    private Object lock = new Object();

    public Foo() {
        
    }

    public void first(Runnable printFirst) throws InterruptedException {
        
        synchronized (lock) {
            // printFirst.run() outputs "first". Do not change or remove this line.
            printFirst.run();
            firstFinished = true;
            lock.notifyAll(); 
        }
    }

    public void second(Runnable printSecond) throws InterruptedException {
        
        synchronized (lock) {
            while (!firstFinished) {
                lock.wait();
            }
        
            // printSecond.run() outputs "second". Do not change or remove this line.
            printSecond.run();
            secondFinished = true;
            lock.notifyAll();
        }
    }

    public void third(Runnable printThird) throws InterruptedException {
        
        synchronized (lock) {
           while (!secondFinished) {
                lock.wait();
            }

            // printThird.run() outputs "third". Do not change or remove this line.
            printThird.run();
        } 
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章