Java锁之可重入锁和递归锁
生活随笔
收集整理的這篇文章主要介紹了
Java锁之可重入锁和递归锁
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
Java鎖之可重入鎖和遞歸鎖
目錄
理論,代碼,小結(jié),學(xué)習(xí)三板斧。
1. Java鎖之可重入鎖和遞歸鎖基本概念
2. Java鎖之可重入鎖和遞歸鎖代碼驗(yàn)證
代碼:
import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock;class Phone implements Runnable {public synchronized void sendSMS() throws Exception {System.out.println(Thread.currentThread().getId() + "\t invoked sendSMS()");sendEmail();}public synchronized void sendEmail() throws Exception {System.out.println(Thread.currentThread().getId() + "\t #####invoked sendEmail()");}Lock lock = new ReentrantLock();@Overridepublic void run() {get();}private void get() {lock.lock();try {//線(xiàn)程可以進(jìn)入任何一個(gè)它已經(jīng)擁有的鎖所同步的代碼塊System.out.println(Thread.currentThread().getId() + "\t invoked get()");set();} catch (Exception e) {e.printStackTrace();} finally {lock.unlock();}}private void set() {lock.lock();try {System.out.println(Thread.currentThread().getId() + "\t #####invoked set()");} catch (Exception e) {e.printStackTrace();} finally {lock.unlock();}} }public class ReenterLockDemo {public static void main(String[] args) {Phone phone = new Phone();new Thread(() -> {try {phone.sendSMS();} catch (Exception e) {e.printStackTrace();}}, "t1").start();new Thread(() -> {try {phone.sendSMS();} catch (Exception e) {e.printStackTrace();}}, "t2").start();try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {e.printStackTrace();}System.out.println();System.out.println();System.out.println();Thread t3 = new Thread(phone, "t3");Thread t4 = new Thread(phone, "t4");t3.start();t4.start();} }編譯結(jié)果:
3. 小結(jié)
總結(jié)
以上是生活随笔為你收集整理的Java锁之可重入锁和递归锁的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Java锁之公平和非公平锁
- 下一篇: Java锁之自旋锁