public class Test
{
public static void main(String[] args)
{
Queue q=new Queue();
Producer p=new Producer();
Consumer c=new Consumer();
p.start();
c.start();
}
}class Producer extends Thread
{
Queue q;
Producer(Queue q)
{
this.q=q;
}
public void run()
{
for(int i=0;i<10;i++)
{
q.put(i);
System.out.println("Producer "+i);
}
}
}class Consumer extends Thread
{
Queue q;
Consumer(Queue q)
{
this.q=q;
}
public void run()
{
while(true)
{
System.out.println("Consumer "+q.get());
}
}
}class Queue
{
int vlaue;
public void put(int i)
{
value=i;
}
public void get()
{
return value;
}
}以上的这段代码,还没有加入wait的时候,就已经编译不过去了,哪位高手帮我看看,谢了

解决方案 »

  1.   

    class MyThread
    {
    public static void main(String [] args)
    {
    PutGet t = new PutGet();
    new Thread(new Product(t)).start();
    new Thread(new Consumer(t)).start();
    }
    }
    class PutGet
    {
    private String name;
    private String sex;
    boolean b=false;
    public void put(String name,String sex)
    {
      if(b)
      try{wait();}catch(Exception e){}
    this.name=name;
    this.sex=sex;
    b=true;
     try{notify();}catch(Exception e){}
    }
    public void get()
    {
    if(!b)
      try{wait();}catch(Exception e){}
    System.out.println(name+"-----"+sex);
    b=false;
        try{notify();}catch(Exception e){}
    }
    }
    class Product implements Runnable
    {
    PutGet q=null;
    int i=0;
    public Product(PutGet q)
    {
    this.q=q;
    }
    public void run()
    {

    while(true)
    {
    synchronized(q)
    {

    if(i==0)
    {
       q.put("ZhangSan","男");
       i=(i+1)%2;
     }
    else
       {
        q.put("LiSi","女");
        i=(i+1)%2;
        }
     
    }
    }
    }
    }
    class Consumer implements Runnable
    {
    PutGet q=null;

    public Consumer(PutGet q)
    {
    this.q=q;
    }
    public void run()
    {
    while(true)
    {
    synchronized(q)
    {
     q.get();
        
    }
    }
    }
    }
    我以前发过一次.你可以看看.根据书上的例子写的
      

  2.   

    很簡單,你在main中調用了兩個線程類的無參構造函數,而在相應的類中卻根本不存在這個構造函數
    在JAVA中一但你自己定義了其他的構造函數,編譯器是不會自動幫你插入那個默認的無參構造函數的