evilgod528 2012-03-29 08:18
浏览 207
已采纳

生产者与消费者问题中,关于对象监视器的问题

 

在下面代码中如果我把生产者和消费者中的同步去掉,把同步shop代码块放在测试端里,为什么会报错,不是同样锁定同步shop对象嘛?
import java.util.Stack;

public class Shop {
    Stack<Integer> stack = new Stack<Integer>();
    
    public boolean empty(){
        return this.stack.empty();
    }
    public Integer peek(){
        return this.stack.peek();
    }
    public Integer pop(){
        return this.stack.pop();
    }
    public Integer push(Integer i){
        return this.stack.push(i) ;
    }
    public  int serach(Integer i){
        return this.stack.search(i) ;
    }
}

 public class Seller extends Thread{

 

 private Shop shop ;
    public Seller(Shop shop){
        this.shop = shop ;
    }
    public void run(){
        synchronized(shop){
            for (int i = 1 ; i <= 30 ; i++) {
                System.out.println( "商店生产了:"+shop.push(new Integer(i))+" 号部件。 " );
                shop.notifyAll() ;
                try {
                    shop.wait() ;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }   
    }
}

 public class Buyer extends Thread {

 private Shop shop ;
    public Buyer(Shop shop){
        this.shop = shop ;
    }
    public void run(){
        synchronized(shop){
            for(int i=1 ; i<= 30 ; i++){
                while(shop.empty()){
                    try {
                        shop.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("顾客买走了编号为:"+shop.pop()+" 号零件");
                shop.notify() ;
            }
        }
    }
}

 public class Client {

   public static void main(String[] args) {
        Shop shop = new Shop() ;
        Seller seller = new Seller(shop) ;
        Buyer buyer = new Buyer(shop) ;
//     synchronized(shop){
            seller.start() ;
            buyer.start() ;
//     }
    }

}
  • 写回答

1条回答 默认 最新

  • zhaoshunxin 2012-03-29 08:57
    关注

    我在里面使用,你在外边同步,木有作用

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘