java重入锁 使用_java重入锁

重入锁

锁作为并发共享数据,保证一致性的工具,在JAVA平台有多种实现(如 synchronized 和 ReentrantLock等等 ) 。这些已经写好提供的锁为我们开发提供了便利。

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

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

下面有两段代码,都是表示锁都是重入锁。

package com.newDemo.controller.test;

public class threadDemo26 implements Runnable {

public synchronized void get() {

System.out.println("name:" + Thread.currentThread().getName() + " get();");

set();

}

public synchronized void set() {

System.out.println("name:" + Thread.currentThread().getName() + " set();");

}

public void run() {

get();

}

public static void main(String[] args) {

threadDemo26 ss = new threadDemo26();

new Thread(ss).start();

new Thread(ss).start();

new Thread(ss).start();

new Thread(ss).start();

}

}

上面这个使用的就是synchronized重入锁

package com.newDemo.controller.test;

import java.util.concurrent.locks.ReentrantLock;

public class threadDemo27 extends Thread {

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();

}

public static void main(String[] args) {

threadDemo27 ss = new threadDemo27();

new Thread(ss).start();

new Thread(ss).start();

new Thread(ss).start();

}

}

上面这个使用的就是ReentrantLock重入锁

点赞

收藏

分享

文章举报

e4bddd717bcc11aa5ad5bd553e4e6c12.png

068be7e19a8fd7ea1cc73db7ddbb42c1.png

努力努力再努力@x

发布了59 篇原创文章 · 获赞 1 · 访问量 400

私信

关注

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值