本文共 1206 字,大约阅读时间需要 4 分钟。
public class Comuser { public static void main(String[] args) { Data data = new Data(); new Thread(()->{ for (int i = 0; i < 20; i++) { data.decrement(); } },"顾客").start(); new Thread(()->{ for (int i = 0; i < 20; i++) { data.increment(); } },"老板").start(); }}class Data{ private int number = 0; //+1 public synchronized void increment() { //同步方法锁的就是this //有数据的时候就等待 if(number != 0) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } number++; System.out.println(Thread.currentThread().getName()+"=>"+number); this.notify(); } //-1 public synchronized void decrement() { //没有数据就等待 if(number == 0) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } number--; System.out.println(Thread.currentThread().getName()+"=>"+number); this.notify(); }}
转载地址:http://dohzi.baihongyu.com/