public class PrintAB {
public static int DEFUALT_TIMES = 10 ;
public static void main ( String[ ] args) {
GuardObject lock = new GuardObject ( ) ;
new Thread ( ( ) - > {
int i = DEFUALT_TIMES;
while ( i-- > 0 ) {
lock. printA ( ) ;
}
} , "t1" ) . start ( ) ;
new Thread ( ( ) - > {
int i = DEFUALT_TIMES;
while ( i-- > 0 ) {
lock. printB ( ) ;
}
} , "t2" ) . start ( ) ;
}
}
class GuardObject {
private boolean flag = true ;
public void printA ( ) {
synchronized ( this ) {
while ( ! this . flag) {
try {
this . wait ( ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
}
System. out. print ( "A" ) ;
flag = false ;
notifyAll ( ) ;
}
}
public void printB ( ) {
synchronized ( this ) {
while ( this . flag) {
try {
this . wait ( ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
}
System. out. print ( "B" ) ;
flag = true ;
notifyAll ( ) ;
}
}
}