zoukankan      html  css  js  c++  java
  • Java 可重入锁

    一般意义上的可重入锁就是ReentrantLock

    http://www.cnblogs.com/hongdada/p/6057370.html

    广义上的可重入锁是指:

    可重入锁,也叫做递归锁,指的是同一线程 外层函数获得锁之后 ,内层递归函数仍然有获取该锁的代码,但不受影响。

    在JAVA环境下 ReentrantLock 和synchronized 都是 可重入锁

    代码:

    public class Main {
        public static void main(String[] args)   {
            Test ss=new Test();
            new Thread(ss).start();
            new Thread(ss).start();
            new Thread(ss).start();
        }
    }
    
    class Test implements Runnable{
    
        public synchronized void get(){
            System.out.println(Thread.currentThread().getId());
            set();
        }
    
        public synchronized void set(){
            System.out.println(Thread.currentThread().getId());
        }
    
        @Override
        public void run() {
            get();
        }
    }
    11
    11
    13
    13
    12
    12
    View Code
    import java.util.concurrent.locks.ReentrantLock;
    
    public class Main {
        public static void main(String[] args)   {
            Test ss=new Test();
            new Thread(ss).start();
            new Thread(ss).start();
            new Thread(ss).start();
        }
    }
    
    class Test implements Runnable {
        ReentrantLock lock = new ReentrantLock();
    
        public void get() {
            lock.lock();
            System.out.println(Thread.currentThread().getId());
            set();
            lock.unlock();
        }
    
        public void set() {
            lock.lock();
            System.out.println(Thread.currentThread().getId());
            lock.unlock();
        }
    
        @Override
        public void run() {
            get();
        }
    }
    12
    12
    13
    13
    11
    11
    View Code

    可以发现同一线程都输出了两次

    可重入锁最大的作用是避免死锁

    http://ifeve.com/java_lock_see4/

  • 相关阅读:
    2015 多校联赛 ——HDU5319(模拟)
    FZU 2158
    FZU 2157 树形DP
    dp之背包总结篇
    JavaScript parseInt() 函数
    JavaScript全局属性/函数
    学生面试心得
    ssh整合
    spring08事务
    JavaScript数组方法大全
  • 原文地址:https://www.cnblogs.com/hongdada/p/6282413.html
Copyright © 2011-2022 走看看