码迷,mamicode.com
首页 > 编程语言 > 详细

Java多线程和并发(九),ReentrantLock(公平锁)

时间:2019-02-11 19:51:56      阅读:225      评论:0      收藏:0      [点我收藏+]

标签:ant   nal   imp   strong   while   lib   catch   thread   rtl   

目录

1.ReentrantLock

2.ReentrantLock的实现

3.synchronized和ReentrantLock的区别

九、ReentrantLock(公平锁)

1.ReentrantLock

 技术图片

2.ReentrantLock的实现

public class ReentrantLockDemo implements  Runnable{
    private static ReentrantLock lock = new ReentrantLock(true);
    @Override
    public void run(){
        while (true){
            try{
                lock.lock();
                System.out.println(Thread.currentThread().getName() + " get lock");
                Thread.sleep(1000);
            } catch (Exception e){
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }
    public static void main(String[] args) {
        ReentrantLockDemo rtld = new ReentrantLockDemo();
        Thread thread1 = new Thread(rtld);
        Thread thread2 = new Thread(rtld);
        thread1.start();
        thread2.start();
    }
}

只有当ReentrantLock构造中传入为true时才是公平锁

3.synchronizedReentrantLock的区别

 技术图片

Java多线程和并发(九),ReentrantLock(公平锁)

标签:ant   nal   imp   strong   while   lib   catch   thread   rtl   

原文地址:https://www.cnblogs.com/xzmxddx/p/10362851.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!