题目要求用线程的通信机制 wait notify 每隔两个数字打一个字母 如12A34B56C....下面这个程序是我写的,我不知道哪里错了,一运行,就停下不动了,我怎么也想不出是怎么回事,请高手帮我看看,问题出在哪里,怎么改,越详细越好,谢谢了。
package thread;public class PrintNum
{
public static void main(String[] args )
{
MyQueue q=new MyQueue();
PrintLetter a=new PrintLetter(q);
PrintNumber b=new PrintNumber(q);
Thread t1=new Thread(a);
Thread t2=new Thread(b);
t2.start();
t1.start();
}
}class PrintLetter implements Runnable
{
MyQueue q=null; PrintLetter(MyQueue q)
{
this.q=q;
}
public void run()
{

for(char ch='A';ch<='Z';ch++)
{
q.printLetter(ch);
}

try
{
Thread.sleep(100); }catch(Exception e)
{
e.printStackTrace();
}
}
}class PrintNumber implements Runnable
{
MyQueue q=null; PrintNumber(MyQueue q)
{
this.q=q;
}
public void run()
{


for(int i=1;i<=52;i++)
{
q.printNunmer(i);
}

try
{
Thread.sleep(100);
}catch(Exception e)
{
e.printStackTrace();
}
}
}class MyQueue
{
int j=0;
int n=0; public synchronized void printLetter(char ch)
{

while(j==1)
{
j=0;
try
{ this.wait(); }catch(Exception e)
{
e.printStackTrace();
} }
j++;
System.out.print(ch+" ");
this.notifyAll(); } public synchronized void printNunmer(int i)
{


while(n==2)
{
n=0;
try
{ this.wait(); }catch(Exception e)
{
e.printStackTrace();
}
}
n++;
System.out.print(i+" ");
this.notifyAll();
}}

解决方案 »

  1.   

    while(j==1) 
    while(n==2) 
    有这两个条件在,run()方法能好像不能运行吧
      

  2.   

    这样试试看.....................class MyQueue 

    int j=0; 
    int n=0; public synchronized void printLetter(char ch) 

    do

      j++; 
      try 
      { 
        this.wait(); 
      }catch(Exception e) 
      { 
        e.printStackTrace(); 
      } 
    }while(j < 1)
    j=0;
    System.out.print(ch+" "); 
    this.notifyAll();
    }
    public synchronized void printNunmer(int i) 

    do

      n++; 
      try 
      { 
         this.wait(); 
      }catch(Exception e) 
      {  e.printStackTrace(); } 
    }while(n < 3)System.out.print(i+" "); this.notifyAll(); 
    } }