public class Synchronized { public static void main(String[] args) { Factory f = new Factory();// ---------------------------------------建立Factory工厂实例 Thread t1 = new Thread() {// ---------------------------------------线程1(生产) public void run() { f.sc();// --------------------------------------------------调用工厂的生产方法 } }; Thread t2 = new Thread() {// ---------------------------------------线程2(消费) public void run() { f.xf();// --------------------------------------------------调用工厂的消费方法 } }; t1.start();// ------------------------------------------------------启动生产方法线程 t2.start();// ------------------------------------------------------启动消费方法线程 } } //****************************************************************************************************** class Factory {// ----------------------------------------------------------工厂 int rl = 10;// ---------------------------------------------------------仓库容量 int sl = 3;// ----------------------------------------------------------实际商品(库存)数量 public void sc() {// ---------------------------------------------------生产方法 try { while (true) {// -----------------------------------------------循环监听 Thread.currentThread().sleep(// ----------------------------生产速度(随机,比消费速度慢,随机数加了200) (int) (Math.random() * 1000 + 200)); synchronized (this) {// ------------------------------------同步锁 System.out.println("生产商品\t库存:" + (++sl));//--------进行生产 if (sl >= rl) {// --------------------------------------判断是否满仓 System.out.println("仓库满了,中止生产"); this.wait();// -------------------------------------中止生产 System.out.println("*************************继续生产"); } if (sl == 6) { this.notify();// -----------------------------------通知消费(设置了商品缓存,库存为0时,生产6件商品以上才通知消费方法) } } } } catch (Exception e) { e.printStackTrace(); } } public void xf() {// ---------------------------------------------------消费方法 try { while (true) {// -----------------------------------------------循环监听 Thread.currentThread().sleep((int) (Math.random() * 1000));//消费速度(随机) synchronized (this) {// ------------------------------------同步锁 System.out.println("消费商品\t库存:" + (--sl) + "-----");//进行消费 if (sl <= 0) {// ---------------------------------------判断是否空仓 System.out.println("仓库没有商品了,中止消费"); this.wait();// -------------------------------------中止消费 System.out.println("*************************继续消费"); } this.notify();// ---------------------------------------通知生产(运行到这里,意味这商品必定被消费了,工厂就开始生产) } } } catch (Exception e) { e.printStackTrace(); } } }
消费速度比生产速度块,因此基本看不到满仓的状况,你能够本身调一下二者之间的速度,这样就能够看到满仓的提示了。缓存
运行结果dom