面试问题

问答1、 下面的代码在绝大部分时间内都运行得很正常,请问在什么情况下会出现问题?问题的根源在哪里?

  import java.util.LinkedList;

  public class Stack {

    LinkedList list = new LinkedList();


    public synchronized void push(Object x) {
      synchronized(list) {
        list.addLast( x );
        notify();
      }
    }

    public synchronized Object pop()
        throws Exception {
      synchronized(list) {
        if( list.size() <= 0 ) {
          wait();
        }
        return list.removeLast();
      }
    }
  }

改为

import java.util.LinkedList;

  public class Stack {

    LinkedList list = new LinkedList();


    public synchronized void push(Object x) {
        list.addLast( x );
        notify();
     }

    public synchronized Object pop()
        throws Exception {
        if( list.size() <= 0 ) {
          wait();
        }
        return list.removeLast();
    }
  }

你可能感兴趣的:(面试问题)