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