本帖最后由 刘学明 于 2013-5-2 10:25 编辑
首先 Lock是 JDK1.5版本后的新特性
Lock替代了synchronized
Condition对象替代了锁对象
一:代码层的区别:- public void method(){
- synchronized(this){ //旧锁 ,无需人工释放
- try(this.wait()}catch(Exception e){}
- System.out.println();
- this.notifyAll();
- }
- }
- public void method2(){
- Lock lock = new ReentrantLock();
- Condition condition = lock.newCondition();
- lock.lock();//上锁
- try{
- try{condition.await();}catch(Exception e){}
- System.out.println("..");
- condition.signalAll();
- }finally{
- lock.unlock();
- }
- }
复制代码 在高并发时,Lock性能 优势很明显 ,在低并发时,synchronized也能取得优势 。
代码示例:- lass Resource
- {
- private String name;
- private int count = 1;
- private boolean flag = false;
- // t1 t2
- private Lock lock = new ReentrantLock();
- private Condition condition_pro = lock.newCondition(); //当多线程并发时 使用Lock机制可以创建两个Condition对象
- private Condition condition_con = lock.newCondition();
- public void set(String name)throws InterruptedException
- {
- lock.lock();
- try
- {
- while(flag)
- condition_pro.await();//t1,t2 //冻结生产方
- this.name = name+"--"+count++;
- System.out.println(Thread.currentThread().getName()+"...生产者.."+this.name);
- flag = true;
- condition_con.signal();// 可以只唤醒消费方,而没有唤醒生产方
- }
- finally
- {
- lock.unlock();//释放锁的动作一定要执行。
- }
- }
- // t3 t4
- public void out()throws InterruptedException
- {
- lock.lock();
- try
- {
- while(!flag)
- condition_con.await();//冻结消费方
- System.out.println(Thread.currentThread().getName()+"...消费者........."+this.name);
- flag = false;
- condition_pro.signal(); //只唤醒生产方 没唤醒消费方
- }
- finally
- {
- lock.unlock();
- }
-
- }
- }
- class Producer implements Runnable
- {
- private Resource res;
- Producer(Resource res)
- {
- this.res = res;
- }
- public void run()
- {
- while(true)
- {
- try
- {
- res.set("+商品+");
- }
- catch (InterruptedException e)
- {
- }
-
- }
- }
- }
- class Consumer implements Runnable
- {
- private Resource res;
- Consumer(Resource res)
- {
- this.res = res;
- }
- public void run()
- {
- while(true)
- {
- try
- {
- res.out();
- }
- catch (InterruptedException e)
- {
- }
- }
- }
- }
复制代码 综合来看,对于所有的高并发情况,采用Lock加锁是最优选择, 但是由于历史遗留等问题 synchronized也还是不能完全淘汰 同时 在低并发的情况下,synchronized的性能还是比Lock要好的 |