public class PrintStringInSequenceUsingWaitNotify {
private int strTotalNums;
private int times;
private int state;
private static final Object LOCK = new Object();
public PrintStringInSequenceUsingWaitNotify(int strTotalNums, int times) {
this.times = times;
this.strTotalNums = strTotalNums;
}
public void printLetter(String str, int seq) {
for (int i = 0; i < times; i++) {
synchronized (LOCK) {
while (state % strTotalNums != seq) {
try {
LOCK.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
++state;
System.out.print(str);
LOCK.notifyAll();
}
}
}
}
public class Print {
public static void main(String[] args) {
PrintStringInSequenceUsingWaitNotify printer = new PrintStringInSequenceUsingWaitNotify(3, 10);
new Thread(() -> {
printer.printLetter("A", 0);
}).start();
new Thread(() -> {
printer.printLetter("B", 1);
}).start();
new Thread(() -> {
printer.printLetter("C", 2);
}).start();
}
}