Suppose we have a class:

1
2
3
4
5
public class Foo {
public void first() { print("first"); }
public void second() { print("second"); }
public void third() { print("third"); }
}

The same instance of Foo will be passed to three different threads. Thread A will call first(), thread B will call second(), and thread C will call third(). Design a mechanism and modify the program to ensure that second() is executed after first(), and third() is executed after second().

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Foo {

public Foo() {

}

public void first(Runnable printFirst) throws InterruptedException {

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

public void second(Runnable printSecond) throws InterruptedException {

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

public void third(Runnable printThird) throws InterruptedException {

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

Semaphore

Official:

1
2
3
4
5
/**
* A counting semaphore. Conceptually, a semaphore maintains a set of
* permits. Each {@link #acquire} blocks if necessary until a permit is
* available, and then takes it. Each {@link #release} adds a permit,
* potentially releasing a blocking acquirer. ...

“Semaphore is a bowl of marbles”. If you need a marble, and there are none, you wait. You wait until there is one marble and then you take it. If you release(), you will add one marble to the bowl. If you release(100), you will add 100 marbles to the bowl.

With semaphores, you can start out with 1 permit or 0 permits or 100 permits. A thread can take permits (up until it’s empty) or put many permits at a time.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import java.util.concurrent.*;

class Foo {

Semaphore s2, s3;

public Foo() {

// both: 0 permit, supressed running
s2 = new Semaphore(0);
s3 = new Semaphore(0);
}

public void first(Runnable printFirst) throws InterruptedException {

// printFirst.run() outputs "first". Do not change or remove this line.
printFirst.run();
s2.release();
}

public void second(Runnable printSecond) throws InterruptedException {

// printSecond.run() outputs "second". Do not change or remove this line.
s2.acquire();
printSecond.run();
s3.release();
}

public void third(Runnable printThird) throws InterruptedException {

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