public class Consumer extends Thread
{
    private List list;
    
    public Consumer(List list)
    {
        this.list = list;
    }
    
    public void run()
    {
        
        synchronized (list)
        {
            while (list.size() == 0)
            {
                try
                {
                    list.wait();        //为什么不能用this.wait()
                }
                catch (InterruptedException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            list.remove(0);
            try
            {
                Thread.sleep(2000);        //为什么不能用this.sleep
            }

解决方案 »

  1.   

    1、用this.wait()和list.wait()的区别:
    list.wait()这个list这个资源进入等待状态,也就是要使用它的话必须notify它,如果用this.wait()表示当前这个Consumer类的示例对象进入资源等待状态,那么里面的所有属性方法都不能使用(静态的好象可以用),当然这个list也不能使用,也就是说,this.wait()的范围要比list.wait()范围大。
    2、Thread.sleep()和this.sleep()
    你可以去查查api:
    sleep
    public static void sleep(long millis) throws InterruptedException
    它是static的方法,这种方法建议采用 类名.方法名 的方式调用,而不是用某一个 引用变量.方法名 来调用。原因在于静态方法归属于类而不是某一个引用对象
      

  2.   


     synchronized (list)同步块就是用的list对象,wait()和notify()方法,应该操作于list对象。静态方法,用类名来调用,当然对象也可以,但这就违背了静态方法的原则了。
      

  3.   

    Javadoc:
    java.object.wait():
    Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. In other words, this method behaves exactly as if it simply performs the call wait(0). 
    The current thread must own this object's monitorthis.wait(),当前线程进入等待。list.wait()只是这个资源进入等待. sleep那个就像2L说的,没区别.建议用类访问
      

  4.   

    就说wait因为当前线程获得的是list对象的monitor,而不是this的monitor,否则IllegalMonitorStateException