/*
 * Two Comedians share a Microphone with wait() and notify()
 */
public class ConversationThree {
    Microphone mic;

    public static void main(String[] args) {
        new ConversationThree();
    }

    public ConversationThree() {
        mic = new Microphone();
        new Thread(new Comedian(Routine.A)).start();
        new Thread(new Comedian(Routine.B)).start();
    }

    // Each comedian has a routine
    class Comedian implements Runnable {
        String[] routine;

        public Comedian(String[] routine) {
            this.routine = routine;
        }

        public void run() {
            // synchronize on the mic
            synchronized (mic) {
                for (int i = 0; i < routine.length; i++) {
                    mic.talk(routine[i]);
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {}
                    // pass the mic when you're done
                    mic.pass(i == routine.length - 1);
                }
            }
        }
    }

    // Speak into the microphone
    class Microphone {
        public void talk(String what) {
            for (int i = 0; i < what.length(); i++) {
                System.out.print(what.charAt(i));

                if (what.charAt(i) == ' ') {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {}
                }
            }
            System.out.println();
        }

        public void pass(boolean finished) {
            // notify the other guy that we're passing him the mic
            notify();
            if (!finished) {
                // wait until the other guy passes us the mic again
                try {
                    wait();
                } catch (InterruptedException e) {}
            }
        }
    }
}

