public class Tongywo { public static void main(String[] args) { // TODO Auto-generated method stub Shangdian0 sd=new Shangdian0(100); Goumai0 no1=new Goumai0(70, sd, "No.1"); Goumai0 no2=new Goumai0(80, sd, "No.2"); no1.start(); no2.start(); } } class Shangdian0{ int kucun=0; public Shangdian0(int kucun){ this.kucun=kucun; } public synchronized void goumai(int i){ if(i<kucun){ kucun-=i; System.out.println(Thread.currentThread().getName()+"购买"+i+"本"); System.out.println("商店剩余"+kucun+"本"); } else{ System.out.println("库存量不够"); } } } class Goumai0 extends Thread{ int i; Shangdian0 sd; public Goumai0(int i, Shangdian0 sd, String name){ this.i=i; this.sd=sd; this.setName(name); } public void run(){ sd.goumai(i); } }
时间: 2024-12-29 11:57:12