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 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用