1 import java.util.concurrent.locks.Condition; 2 import java.util.concurrent.locks.Lock; 3 import java.util.concurrent.locks.ReentrantLock; 4 5 /** 6 * 模拟增1和减一交替操作, 7 * 8 * 1 线程 操作(方法) 资源类 9 * 2 判断 干活 通知 10 * 3 防止虚假唤醒机制 11 */ 12 class ShareData{ 13 private int number=0; 14 private Lock lock=new ReentrantLock(); 15 private Condition condition=lock.newCondition(); 16 public void increment() throws Exception{ 17 lock.lock(); 18 System.out.println("increment加锁"+lock); 19 try{ 20 while(number!=0){ 21 System.out.println("while_in循环"+lock); 22 condition.await(); 23 } 24 number=number+1; 25 System.out.println(Thread.currentThread().getName()+"\t "+number); 26 condition.signalAll(); 27 }catch (Exception e){ 28 29 }finally { 30 lock.unlock(); 31 System.out.println("increment解锁"+lock); 32 } 33 } 34 public void decrement() throws Exception{ 35 lock.lock(); 36 System.out.println("decrement加锁"+lock); 37 try{ 38 while(number!=1){ 39 System.out.println("while_de循环"+lock); 40 condition.await(); 41 } 42 number=number-1; 43 System.out.println(Thread.currentThread().getName()+"\t "+number); 44 condition.signalAll(); 45 }catch (Exception e){ 46 47 }finally { 48 lock.unlock(); 49 System.out.println("decrement解锁"+lock); 50 } 51 } 52 53 } 54 class ShareData_sync{ 55 private int number=1; 56 public synchronized void increment() throws Exception{ 57 try{ 58 while(number!=1){ 59 this.wait(); 60 } 61 number=number+1; 62 System.out.println(Thread.currentThread().getName()+"\t "+number); 63 this.notifyAll(); 64 }catch (Exception e){ 65 66 } 67 } 68 public synchronized void decrement() throws Exception{ 69 try{ 70 while(number!=2){ 71 this.wait(); 72 } 73 number=number-1; 74 System.out.println(Thread.currentThread().getName()+"\t "+number); 75 this.notifyAll(); 76 }catch (Exception e){ 77 78 } 79 } 80 81 } 82 83 public class ProdConsumer_TraditionDemo { 84 85 public static void main(String[] args) { 86 ShareData shareData=new ShareData(); 87 new Thread(()->{ 88 for (int i = 0; i <5 ; i++) { 89 try { 90 shareData.increment(); 91 } catch (Exception e) { 92 e.printStackTrace(); 93 } 94 } 95 },"AA").start(); 96 new Thread(()->{ 97 for (int i = 0; i <5 ; i++) { 98 try { 99 shareData.decrement(); 100 } catch (Exception e) { 101 e.printStackTrace(); 102 } 103 } 104 105 },"BB").start(); 106 } 107 }