Semaphore信號量保證多線程執行順序

import java.util.concurrent.Semaphore;

public class ApplicationDemo10 {

    public static void main(String[] args) throws InterruptedException {
        Foo foo = new Foo();

        int[] arr = new int[]{2,3,1};
        for(int i = 0; i < arr.length; i++){
            if(i == 0){
                foo.first(()-> System.out.println("first"));
            }else if(i == 1){
                foo.second(()-> System.out.println("second"));
            }else if(i == 2){
                foo.third(()-> System.out.println("third"));
            }
        }
    }

}

class Foo {

    Semaphore semaphore2 = new Semaphore(0);
    Semaphore semaphore3 = new Semaphore(0);

    public Foo() {

    }

    public void first(Runnable printFirst) throws InterruptedException {
        printFirst.run();
        semaphore2.release();
    }

    public void second(Runnable printSecond) throws InterruptedException {
        semaphore2.acquire();
        printSecond.run();
        semaphore3.release();
    }

    public void third(Runnable printThird) throws InterruptedException {
        semaphore3.acquire();
        printThird.run();
    }
}

運行結果:

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