溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Java中可重入鎖的作用有哪些

發布時間:2021-03-02 15:13:14 來源:億速云 閱讀:522 作者:戴恩恩 欄目:編程語言

這篇文章主要介紹了Java中可重入鎖的作用有哪些,億速云小編覺得不錯,現在分享給大家,也給大家做個參考,一起跟隨億速云小編來看看吧!

Java可以用來干什么

Java主要應用于:1. web開發;2. Android開發;3. 客戶端開發;4. 網頁開發;5. 企業級應用開發;6. Java大數據開發;7.游戲開發等。

可重入鎖,也叫做遞歸鎖,指的是同一線程 外層函數獲得鎖之后 ,內層遞歸函數仍然有獲取該鎖的代碼,但不受影響。

在JAVA環境下 ReentrantLock 和synchronized 都是 可重入鎖。

下面是使用實例:

package reentrantLock;
 
public 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();
  }
  public static void main(String[] args) {
    Test ss=new Test();
    new Thread(ss).start();
    new Thread(ss).start();
    new Thread(ss).start();
  }
}

運行截圖:

Java中可重入鎖的作用有哪些

package reentrantLock;
 
import java.util.concurrent.locks.ReentrantLock;
 
public 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();
  }
 
  public static void main(String[] args) {
    Test ss = new Test();
    new Thread(ss).start();
    new Thread(ss).start();
    new Thread(ss).start();
  }
}

Java中可重入鎖的作用有哪些

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

我們以自旋鎖作為例子,

public class SpinLock {
	private AtomicReference<Thread> owner =new AtomicReference<>();
	public void lock(){
		Thread current = Thread.currentThread();
		while(!owner.compareAndSet(null, current)){
		}
	}
	public void unlock (){
		Thread current = Thread.currentThread();
		owner.compareAndSet(current, null);
	}
}

對于自旋鎖來說,

1、若有同一線程兩調用lock() ,會導致第二次調用lock位置進行自旋,產生了死鎖說明這個鎖并不是可重入的。(在lock函數內,應驗證線程是否為已經獲得鎖的線程)

2、若1問題已經解決,當unlock()第一次調用時,就已經將鎖釋放了。實際上不應釋放鎖。(采用計數次進行統計)修改之后,如下:

public class SpinLock1 {
	private AtomicReference<Thread> owner =new AtomicReference<>();
	private int count =0;
	public void lock(){
		Thread current = Thread.currentThread();
		if(current==owner.get()) {
			count++;
			return ;
		}
 
		while(!owner.compareAndSet(null, current)){
 
		}
	}
	public void unlock (){
		Thread current = Thread.currentThread();
		if(current==owner.get()){
			if(count!=0){
				count--;
			}else{
				owner.compareAndSet(current, null);
			}
 
		}
 
	}
}

以上就是億速云小編為大家收集整理的Java中可重入鎖的作用有哪些,如何覺得億速云網站的內容還不錯,歡迎將億速云網站推薦給身邊好友。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女