JAVA进阶之ReenTrantLock

 
import java.util.concurrent.locks.ReentrantLock;
 
/**
 * Created by haicheng.lhc on 17/05/2017.
 *
 * @author haicheng.lhc
 * @date 2017/05/17
 */
public class ReentrantLockTest extends Thread {
 
    public static ReentrantLock lock = new ReentrantLock();
    public static int i = 0;
 
    public ReentrantLockTest(String name) {
        super.setName(name);
    }
 
    @Override
    public void run() {
        for (int j = 0; j < 10000000; j++) {
            lock.lock();
            try {
                System.out.println(this.getName() + " " + i);
                i++;
            } finally {
                lock.unlock();
            }
        }
    }
 
    /**
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {
        ReentrantLockTest test1 = new ReentrantLockTest("thread1");
        ReentrantLockTest test2 = new ReentrantLockTest("thread2");
 
        test1.start();
        test2.start();
        test1.join();
        test2.join();
        System.out.println(i);
    }
}
 

ReenTrantCock的优点是比较灵活但使用麻烦。需要finally代码块中解锁。

  • java中已经有了内置锁:synchronized,synchronized的特点是使用简单,一切交给JVM去处理,不需要显示释放
  • 从用法上可以看出,与synchronized相比, ReentrantLock就稍微复杂一点。因为必须在finally中进行解锁操作,如果不在 finally解锁,有可能代码出现异常锁没被释放,
  • 那么为什么要引入ReentrantLock呢?

  • 在jdk1.5里面,ReentrantLock的性能是明显优于synchronized的,但是在jdk1.6里面,synchronized做了优化,他们之间的性能差别已经不明显了。
  • ReentrantLock并不是一种替代内置加锁的方法,而是作为一种可选择的高级功能。
  • 相比于synchronizedReentrantLock在功能上更加丰富,它具有可重入、可中断、可限时、公平锁等特点。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值