package test;
public class SycnStack{ private static Integer value =0; private static Object LOCK = new Object(); public static void main(String[] args) { SycnStack ss = new SycnStack(); ss.new AThread().start(); ss.new BThread().start(); } public static void produce() { synchronized (LOCK) { while(value == 3) { System.out.println("值超过3,停止增加"); try { LOCK.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } value ++; System.out.println("生产第 " + value + "个"); LOCK.notify(); } } public static void custom() { synchronized (LOCK) { while(value == 0){ System.out.println("值小于或等于0,停止减少"); try { LOCK.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("消费第 " + value + "个"); value --; LOCK.notify(); } } class AThread extends Thread { public void run() { while(true) { produce(); try { Thread.sleep((long)(Math.random() * 3000)); } catch (InterruptedException e) { } } } } class BThread extends Thread { public void run() { while(true) { custom(); try { Thread.sleep((long)(Math.random() * 3000)); } catch (InterruptedException e) { } } } } }