package demo;
public class Demo3 {
public static void main(String[] args) {
final Print_ print = new Print_();
new Thread(new Runnable() {
public void run() {
for(int i=0 ;i<10 ;i++) {
print.Print_A();
}
}
}).start();
new Thread(new Runnable() {
public void run() {
for(int i=0 ;i<10 ;i++) {
print.Print_B();
}
}
}).start();
}
}
class Print_{
private boolean flag=true;
public synchronized void Print_A(){
while(!flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print("A");
flag=false;
this.notify();
}
public synchronized void Print_B(){
while(flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("B");
flag=true;
this.notify();
}
}
输出结果:
AB
AB
AB
AB
AB
AB
AB
AB
AB
AB