package Pta;
import java.util.concurrent.Semaphore;
public class Test {
public static void main(String[] args) throws InterruptedException {
Foo foo = new Foo();
Runnable printFirst = new Runnable() {
@Override
public void run() {
System.out.println("first");
}
};
Runnable printSecond = new Runnable() {
@Override
public void run() {
System.out.println("second");
}
};
Runnable printThird = new Runnable() {
@Override
public void run() {
System.out.println("third");
}
};
new Thread(new Runnable() {
@Override
public void run() {
try {
foo.third(printThird);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
try {
foo.first(printFirst);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
try {
foo.second(printSecond);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
class Foo {
Semaphore s1=new Semaphore(1);
Semaphore s2=new Semaphore(0);
Semaphore s3=new Semaphore(0);
public Foo() {
}
public void first(Runnable printFirst) throws InterruptedException {
s1.acquire();
printFirst.run();
s2.release();
}
public void second(Runnable printSecond) throws InterruptedException {
s2.acquire();
printSecond.run();
s3.release();
}
public void third(Runnable printThird) throws InterruptedException {
s3.acquire();
printThird.run();
}
}