public class PrintTest
{
static int index;
static int count = 0; public PrintTest()
{
index = 0;
} public synchronized void printA()
{
if (index % 3 == 0)
{
index++;
System.out.print("A");
count++;
notifyAll();
} else
{
try
{
wait();
} catch (Exception e)
{
System.out.println(e.getMessage());
}
} } public synchronized void printB()
{
if (index % 3 == 1)
{ index++;
System.out.print("B");
count++;
notifyAll();
} else
{
try
{
wait();
} catch (Exception e)
{
System.out.println(e.getMessage());
}
} } public synchronized void printC()
{
if (index % 3 == 2)
{
index++;
System.out.print("C");
count++;
notifyAll();
} else
{
try
{
wait();
} catch (Exception e)
{
System.out.println(e.getMessage());
}
} } public static void main(String[] s)
{
PrintTest pt = new PrintTest();
PrintA pa = new PrintA(pt);
PrintB pb = new PrintB(pt);
PrintC pc = new PrintC(pt);
pa.start();
pb.start();
pc.start();
}}class PrintA extends Thread
{ PrintTest pt; public PrintA(PrintTest pt)
{
this.pt = pt;
} @Override
public void run()
{
while(pt.count < 30)
{
pt.printA();
}

// for (int i = 0; i < 10; i++)
// {
// pt.printA();
// }
}}class PrintB extends Thread
{ PrintTest pt; public PrintB(PrintTest pt)
{
this.pt = pt;
} @Override
public void run()
{
while(pt.count < 30)
{
pt.printB();

}

// for (int i = 0; i < 10; i++)
// {
// pt.printB();
// }
}}class PrintC extends Thread
{ PrintTest pt; public PrintC(PrintTest pt)
{
this.pt = pt;
} @Override
public void run()
{
while(pt.count < 30)
{
pt.printC();

}

// for (int i = 0; i < 10; i++)
// {
// pt.printC();
// }
}}

解决方案 »

  1.   

    因为系统的时间片轮转是随机的,有可能连续的给同一个PrintC中的run()时间,那么for循环的i不断增加,但是printC()方法还是等待,这样没等你的10次ABC打印完,for循环就用光了。跟踪调试一下就能搞定啦。
      

  2.   

    兄弟   能再解释清楚些吗,谢谢了  单步调试的结果也很奇葩你这个结果理想的情况下能输出5次ABC,首先你在A、B、C的3个for循环上打上断点,然后调试,你会发现,执行PrintA中run()方法时,i=0,第一次,不等待,直接打印A,然后for循环继续,i=1,这一次wait()了,不打印,然后执行其他的打印,单以PrintA为例,你每打印一次,用了两个i,那么i<10,你最多打印5次。不知道这回你懂不懂,不懂就自己再研究吧。
      

  3.   

    楼上都是正解,比如线程printA执行printA()方法、但是因为index值不符合所以走wait分支,这时候没走打印分支,但是呢 、for循环里已经用了一次循环了。
      

  4.   

    所以,循环不能用10,因为有些循环用来走等待分支了,没走打印。这里循环的条件统一是pt.index<30