public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int count = Integer.parseInt(br.readLine());
StringBuilder totalSB = new StringBuilder();
Runner runner = new Runner(totalSB, count);
new Thread(runner, "A").start();
new Thread(runner, "B").start();
new Thread(runner, "C").start();
new Thread(runner, "D").start();
// 阻塞直到计数器减为0
while (Runner.count != 0) {}
System.out.println(totalSB.toString());
}
static class Runner implements Runnable {
/**
* 对象锁
*/
private Object lock = new Object();
/**
* 最终显示结果
*/
private StringBuilder totalSB;
/**
* 全线程可见的索引位置
*/
private volatile int index = 0;
/**
* 单词表
*/
private final String[] words = {"A","B","C","D"};
/**
* 全线程可见的计数器
*/
public static volatile int count;
public Runner(StringBuilder totalSB, int count) {
this.totalSB = totalSB;
this.count = count;
}
@Override
public void run() {
String threadName = Thread.currentThread().getName();
synchronized (lock) {
while (count > 0) {
if (words[index].equals(threadName)) {
totalSB.append(threadName);
if (index == 3) {
index = 0;
} else {
index++;
}
if ("D".equals(threadName)) {
count--;
}
}
try {
lock.wait(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.notifyAll();
}
}
}
}