class Q 
{
private String name="张三";
private String sex="男";
public  synchronized void put(String name,String sex)
{
this.name=name;
/*try
{
Thread.sleep(10);
}
catch (Exception e)
{
System.out.println(e.getMessage());
}*/
this.sex=sex;
}
public  synchronized void get()
{
System.out.println(name+"------>"+sex);
}
}clsss 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("李四","女");
}

}
}
}
class Consumer implements Runnable
{
Q q=null;
public  Consumer(Q q)
{
this.q=q;
}
public void run()
{
while (true)

q.get();
}
}
}
public class ThreadCommunication 
{
    public static void main(String[] args)
{
    Q q=new Q();
    new Thread((new Producer()).q).start();
        new Thread((new consumer()).q).start();
}
}
以上语句为什么执行不成功,谢谢!!!

解决方案 »

  1.   

    答:main中代码应改为如下:public static void main(String[] args) 

        Q q=new Q(); 
        new Thread((new Producer(q))).start(); 
            new Thread((new Consumer(q))).start(); 

      

  2.   

    谢谢了,不过我执行的时候出现的是这个错误:
    ThreadCommunication.java:24:需要为class、interface或enum class Producer implements Runnable.......后面还有很多行,好像都是同样的错误。
      

  3.   

    除了“clsss Producer implements Runnable”中的那个class写错了外,执行了一下,没什么问题
      

  4.   

    好的,太感谢了,我真是太粗心了,昨天下午找了一下午都没有找到问题。对了再问您一个弱弱的问题,q应该当作Producer和Consumer的内部类的还是一个参数呢?