public class Test {
public static void main ( String[ ] args) throws Exception {
MyPrinter myPrinter = new MyPrinter ( ) ;
new Thread ( ( ) - > {
for ( int i= 0 ; i< 3 ; i++ ) {
myPrinter. printA ( ) ;
}
} ) . start ( ) ;
new Thread ( ( ) - > {
for ( int i= 0 ; i< 3 ; i++ ) {
myPrinter. printB ( ) ;
}
} ) . start ( ) ;
new Thread ( ( ) - > {
for ( int i= 0 ; i< 3 ; i++ ) {
myPrinter. printC ( ) ;
}
} ) . start ( ) ;
}
}
class MyPrinter {
String printFlag= "A" ;
public synchronized void printA ( ) {
while ( ! printFlag. equals ( "A" ) ) {
try {
this . wait ( ) ;
} catch ( Exception e) {
e. printStackTrace ( ) ;
}
}
System. out. println ( "A" ) ;
printFlag = "B" ;
this . notifyAll ( ) ;
}
public synchronized void printB ( ) {
while ( ! printFlag. equals ( "B" ) ) {
try {
this . wait ( ) ;
} catch ( Exception e) {
e. printStackTrace ( ) ;
}
}
System. out. println ( "B" ) ;
printFlag = "C" ;
this . notifyAll ( ) ;
}
public synchronized void printC ( ) {
while ( ! printFlag. equals ( "C" ) ) {
try {
this . wait ( ) ;
} catch ( Exception e) {
e. printStackTrace ( ) ;
}
}
System. out. println ( "C" ) ;
printFlag = "A" ;
this . notifyAll ( ) ;
}
}
A
B
C
A
B
C
A
B
C