public class Foo { public void one() { print("one"); } public void two() { print("two"); } public void three() { print("three"); } } The same instance of Foo will be passed to three different threads. Thread A will call one(), thread B will call two(), and thread C will call three(). Design a mechanism and modify the program to ensure that two() is executed after one(), and three() is executed after two().
class Foo { private CountDownLatch c2; private CountDownLatch c3;
public Foo() { c2 = new CountDownLatch(1); c3 = new CountDownLatch(1); }
public void first(Runnable printFirst) throws InterruptedException { // printFirst.run() outputs "first". Do not change or remove this line. printFirst.run(); c2.countDown(); }
public void second(Runnable printSecond) throws InterruptedException { c2.await(); // printSecond.run() outputs "second". Do not change or remove this line. printSecond.run(); c3.countDown(); }
public void third(Runnable printThird) throws InterruptedException { c3.await(); // printThird.run() outputs "third". Do not change or remove this line. printThird.run(); } }
public void first(Runnable printFirst) throws InterruptedException { // printFirst.run() outputs "first". Do not change or remove this line. printFirst.run(); flag = 2; }
public void second(Runnable printSecond) throws InterruptedException { while(flag != 2); // printSecond.run() outputs "second". Do not change or remove this line. printSecond.run(); flag = 3; }
public void third(Runnable printThird) throws InterruptedException { while(flag != 3); // printThird.run() outputs "third". Do not change or remove this line. printThird.run(); } }