SDK1.5版本以后对synchronized的升级,其思想是:将同步和锁封装成对象,其对象中包含操作锁的动作。
代码:
1 //1、导入包 2 import java.util.concurrent.locks.*; 3 class Resource 4 { 5 private String name; 6 private int count=1; 7 private boolean flag=false; 8 9 //创建互斥锁(相当于synchronized) 10 Lock lock = new ReentrantLock(); 11 //创建锁对象(相当于Object对象) 12 Condition producer_con = lock.newCondition(); 13 Condition consumer_con = lock.newCondition(); 14 15 public void set(String name) 16 { 17 lock.lock(); 18 try 19 { 20 while(flag) 21 try{producer_con.await();}catch(InterruptedException e){} 22 this.name=name+count; 23 count++; 24 System.out.println(Thread.currentThread().getName() + "...生产者..." + this.name); 25 flag = true; 26 consumer_con.signal(); 27 } 28 finally 29 { 30 lock.unlock(); 31 } 32 } 33 34 public void out() 35 { 36 lock.lock(); 37 try 38 { 39 while(!flag) 40 try{consumer_con.await();}catch(InterruptedException e){} 41 System.out.println(Thread.currentThread().getName() + "==消费者==" + this.name); 42 flag = false; 43 producer_con.signal(); 44 } 45 finally 46 { 47 lock.unlock(); 48 } 49 } 50 } 51 52 //定义线程任务(生产者线程) 53 class Producer implements Runnable 54 { 55 private Resource r; 56 57 Producer(Resource r) 58 { 59 this.r=r; 60 } 61 public void run() 62 { 63 while(true) 64 { 65 r.set("商品"); 66 } 67 } 68 } 69 //定义线程任务(消费者线程) 70 class Consumer implements Runnable 71 { 72 private Resource r; 73 74 Consumer(Resource r) 75 { 76 this.r=r; 77 } 78 79 public void run() 80 { 81 while(true) 82 { 83 r.out(); 84 } 85 } 86 } 87 88 class ProducerConsumerDemo 89 { 90 public static void main(String[] args) 91 { 92 //实例化共享资源 93 Resource r = new Resource(); 94 //实例化线程任务,指定共享资源 95 Producer p=new Producer(r); 96 Consumer c=new Consumer(r); 97 //实例化线程,指定线程任务 98 Thread t0=new Thread(p); 99 Thread t1=new Thread(p); 100 Thread t2=new Thread(c); 101 Thread t3=new Thread(c); 102 //开启线程,执行线程任务中的run方法 103 t0.start(); 104 t1.start(); 105 t2.start(); 106 t3.start(); 107 } 108 }
结果:
lock就是对同步的封装那就有关系和区别: