1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
|
public class ProdConsumeTranditionalDemo {
public static void main(String[] args) {
ShareData shareData=new ShareData(); for(int i=0;i<10;i++){ new Thread(()->{ shareData.increment(); System.out.println(Thread.currentThread().getName()+"\t 生产成功!"); },String.valueOf(i)).start(); } for(int i=0;i<10;i++){ new Thread(()->{ shareData.decrement(); System.out.println(Thread.currentThread().getName()+"\t 消费成功!"); },String.valueOf(i)).start(); }
} }
class ShareData{ private Integer num=0; private Lock lock=new ReentrantLock(); private Condition condition=lock.newCondition();
public void increment(){ lock.lock(); try{ while (num!=0){ condition.await(); } num++; System.out.println(Thread.currentThread().getName()+"\t"+num); condition.signalAll(); } catch (InterruptedException e) { e.printStackTrace(); } finally{ lock.unlock(); } } public void decrement(){ lock.lock(); try{ while (num==0){ condition.await(); } num--; System.out.println(Thread.currentThread().getName()+"\t"+num); condition.signalAll(); } catch (InterruptedException e) { e.printStackTrace(); } finally{ lock.unlock(); } } }
|