zoukankan      html  css  js  c++  java
  • Java多线程和并发(九),ReentrantLock(公平锁)

    目录

    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的区别

     

  • 相关阅读:
    第十九天:类和对象
    第十五天:模块
    十四天:匿名函数
    十四天作业
    第十三天:迭代器、递归
    十二天:闭包和装饰器
    一个炒鸡简单的购物车
    十一天
    第十天
    第十天作业
  • 原文地址:https://www.cnblogs.com/xzmxddx/p/10362851.html
Copyright © 2011-2022 走看看