reentrantlock与synchronized

来源:互联网 发布:好看的皮鞋淘宝店铺 编辑:程序博客网 时间:2024/06/05 02:41

读一些源码的时候,经常遇到reentrantlock(可重入锁),与传统的synchronized相比,如果没有什么特殊的要求,建议还是使用synchronized比较好,reentrantlock是jdk5.0推出的,刚推出时其性能比synchronized高出一大截,但是到了jdk1.6及以后,synchronized经过长期的优化后其性能已经与reentrantlock不分高下,但是reentrantlock支持的功能更加强大,典型的例子reentrantlock可以支持公平锁。


reentrantlock的基本使用:

 ReentrantLock lock = new ReentrantLock();        lock.lock();        try {           //some operator        }        finally {            lock.unlock();        }

reentrantlock特殊的地方:

import java.util.concurrent.locks.ReentrantLock;/** *    ┏┓   ┏┓ *   ┏┛┻━━━┛┻┓ *   ┃       ┃ *   ┃   ━   ┃ *   ┃ ┳┛ ┗┳ ┃ *   ┃       ┃ *   ┃   ┻   ┃ *   ┃       ┃ *   ┗━┓   ┏━┛ *     ┃   ┃神兽保佑, 永无BUG! *     ┃   ┃Code is far away from bug with the animal protecting *     ┃   ┗━━━┓ *     ┃       ┣┓ *     ┃       ┏┛ *     ┗┓┓┏━┳┓┏┛ *      ┃┫┫ ┃┫┫ *      ┗┻┛ ┗┻┛ * * @Author: pig * @Date: Created in 下午3:29 17/1/24 * @Description: */public class ReenTrantLockTest {    //默认是非公平锁    private ReentrantLock lock = new ReentrantLock(true);    class A extends Thread {        @Override        public void run() {            try {                lock.lock();                System.out.print("A");            } finally {                lock.unlock();            }        }    }    class B extends Thread {        @Override        public void run() {            try {                lock.lock();                System.out.print("B");            } finally {                lock.unlock();            }        }    }    class C extends Thread {        @Override        public void run() {            try {                lock.lock();                System.out.print("C");            } finally {                lock.unlock();            }        }    }    public void start() {        for (int i=0;i<10;i++) {            Thread a = new A();            a.start();            Thread b = new B();            b.start();            Thread c = new C();            c.start();        }    }    public static void main(String[] args) {        ReenTrantLockTest testLock = new ReenTrantLockTest();        testLock.start();        //ABCABCABCABCABCABCABCABCABCABC        //如果ReentrantLock lock = new ReentrantLock();        //那么结果不能保证ABCABC的顺序    }}

如果是新手,建议还是使用synchronized,简单,不容易出现问题。

0 0
原创粉丝点击