public class Exercise3 {
public static void main(String[] args) {
final Printer p=new Printer();
new Thread(){
public void run()
{
for(int i=0;i<5;i++)
p.print1();
}
}.start();
new Thread(){
public void run()
{
for(int i=0;i<5;i++)
p.print2();
}
}.start();
}
}
class Printer
{
private int turn=1;
public synchronized void print1()
{
if(turn!=1)
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
else
System.out.println("A");
turn=2;
this.notify();
}
public synchronized void print2()
{
if(turn!=2)
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
else
System.out.println("B");
turn=1;
this.notify();
}
}这里为什么只打印了一次A,B???不明白,请高手帮忙讲解一下,谢谢! |
|