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
- ReentrantLock与synchronized比较
- reentrantlock与synchronized
- synchronized与reentrantLock区别
- java ReentrantLock与synchronized
- Synchronized与ReentrantLock
- ReentrantLock与synchronized
- ReentrantLock与synchronized
- reentrantlock与synchronized
- ReentrantLock与Synchronized异同
- ReentrantLock与synchronized
- Synchronized与ReentrantLock区别
- ReentrantLock与synchronized
- ReentrantLock(一):谈谈ReentrantLock与synchronized
- ReentrantLock与synchronized的区别
- ReentrantLock与synchronized的区别
- ReentrantLock与synchronized的区别
- ReentrantLock与synchronized (顶)
- ReentrantLock 与 synchronized 一点区别
- java web中如何使用将数据写入CSV文件中并下载
- 蓝桥杯算法提高 拿糖果
- Spring JDBC 具名参数
- insert时返回键值
- spark-streaming状态流之mapWithState
- reentrantlock与synchronized
- Linux(Centos)之安装Java JDK及注意事项
- 『 Jack_a_Lent_Notes』---三极管的三种工作状态
- C++ static、const以及static const的用法
- Leetcode- 143. Reorder List
- ExtJS学习笔记(十一) Tree的父子级联动选定,和自定义半选状态
- Linux 安装JDK
- 运行caffe自带的两个简单例子
- struts2 1/24 基础配置