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/

  • 相关阅读:
    单例模式
    反射常见方法
    字符流,字节流总结
    泛型限定
    随机数判断最值
    字符流与字节流练习
    文件常见操作属性
    文件过滤器
    字符流读取文件
    目前最流行的IT编程语言
  • 原文地址:https://www.cnblogs.com/hongdada/p/6282413.html
Copyright © 2011-2022 走看看