zoukankan      html  css  js  c++  java
  • 《Java 并发编程》ReentrantLock详细分析

    前言

    原理

    ReentrantLock案例

    import java.util.concurrent.locks.ReentrantLock;
    
    public class ReentrantLockDemo {
    
        public static int k = 0;
    
        public static ReentrantLock reentrantLock = new ReentrantLock();
    
        public static void main(String[] args) {
    
            ReentrantLock reentrantLock = new ReentrantLock();
    
            Thread thread = new Thread(()->{
                reentrantLock.lock(); // 加锁
                try {
                    for (int i = 0; i < 100; i++) {
                        k++;
                    }
                    System.out.println("k="+k);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    reentrantLock.unlock();   // 显示锁,解锁必须放入finally中执行。
                }
            });
            thread.start();
        }
    }

    运行结果:

    源码:

    public ReentrantLock() {
        sync = new NonfairSync();
    }

    默认创建的是非公平锁。

    public ReentrantLock(boolean fair) {
        sync = fair ? new FairSync() : new NonfairSync();
    }

    通过创建对象不同来创建非公平锁。

    公平非公平,原理很简单,公平老老实实加入队列,非公平先试试能不能加锁,不能才加入队列。

    This moment will nap, you will have a dream; But this moment study,you will interpret a dream.
  • 相关阅读:
    Swift # Apple Pay集成
    GitHub Top 100 简介
    一些常用算法
    CocoaPods 建立私有仓库
    安装 CocoaPods & Alcatraz
    iOS程序 # 启动过程
    Apache & WebDav 配置(二)
    SVN & Git (二)
    SVN & Git (一)
    poj 3169 Layout (差分约束)
  • 原文地址:https://www.cnblogs.com/jssj/p/14193319.html
Copyright © 2011-2022 走看看