在下面代码中如果我把生产者和消费者中的同步去掉,把同步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() ;
// } } }