package com.company;
import java.util.LinkedList;
import java.util.Queue;
public class Main {
public static void main(String[] args) throws InterruptedException {
Queue wordList = new LinkedList();
Object todoA = new Object();
Object todoB = new Object();
Object todoC = new Object();
for (int i = 0; i < 100; i++) {
wordList.add('a');
wordList.add('b');
wordList.add("c ");
}
new Thread(new PrintWord("1", wordList, todoA, todoB)).start();
new Thread(new PrintWord("2", wordList, todoB, todoC)).start();
new Thread(new PrintWord("3", wordList, todoC, todoA)).start();
synchronized (todoA) {
todoA.notify();
}
// write your code here
}
public static class PrintWord implements Runnable {
String id;
Queue wordList;
Object todo;
Object todoNext;
private PrintWord(String id, Queue wordList, Object todo, Object todoNext) {
this.id = id;
this.wordList = wordList;
this.todo = todo;
this.todoNext = todoNext;
}
@Override
public void run() {
while (true) {
try {
synchronized (todo) {
todo.wait();
Object _word = wordList.peek();
if (_word != null) {
System.out.print(this.id);
System.out.print(_word);
wordList.remove();
}
synchronized (todoNext) {
todoNext.notifyAll();
}
if (_word == null) break;
}
} catch (InterruptedException e) {
synchronized (todoNext) {
todoNext.notifyAll();
}
e.printStackTrace();
}
}
}
}
}