日期:2014-05-20  浏览次数:20783 次

《java就业培训教程》的一道题
Java code

public class ThreadCommunication_4
{
    public static void main(String[] args)
    {
        Q q= new Q();
        new Thread(new Producer(q)).start();
        new Thread(new Consumer(q)).start();
    }
}
class Q
{
    private String name = "张孝祥";
    private String sex = "男";
    boolean bFull=false;
    
    public synchronized void put(String name, String sex)
    {
        if(bFull)
        {
          try
            {
                wait();
            }
            catch(Exception e)
            {
                System.out.println(e.getMessage());
            }
        }
            this.name = name;
            try
            {
                Thread.sleep(10);
            }
            catch(Exception e)
            {
                System.out.println(e.getMessage());
            }
        this.sex=sex;
        bFull = true;
        notify();
    }
    public synchronized void get()
    {
        if(!bFull)
        {
            try
            {
                    wait();
            }
            catch(Exception e)
            {
                System.out.println(e.getMessage());
            }
        }
        System.out.println(name+"----->"+sex);
        bFull=false;
        notify();
    }
}
class  Producer implements Runnable
{
    Q q = null;
    public Producer(Q q)
    {
        this.q=q;
    }
    public void run()
    {
        int i = 0;
        while(true)
        {
            if(i == 0)
            {
                q.put("张孝祥","男");
            }
            else
            {
                q.put("陈琼","女");
            }
            i = (i+1)%2;
        }
    }
}
class Consumer implements Runnable
{
    Q q =null;
    public Consumer(Q q)
    {
        this.q=q;
    }
    public void run()
    {
        q.get();
    }



为什么测试的结果和书上的不一样啊 
书上的结果是:
-----------------------
张孝祥----->男
陈琼------>女
......
-----------------------
我的结果只有
---------------
张孝祥----->男
---------------
这是为什么???

------解决方案--------------------
Java code
 public void run()
    {
        q.get();
    }