欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

簡(jiǎn)單了解Java中的可重入鎖

 更新時(shí)間:2019年11月27日 09:45:55   作者:syrdbt  
這篇文章主要介紹了簡(jiǎn)單了解Java中的可重入鎖,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

這篇文章主要介紹了簡(jiǎn)單了解Java中的可重入鎖,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

本文里面講的是廣義上的可重入鎖,而不是單指JAVA下的ReentrantLock。

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

在JAVA環(huán)境下 ReentrantLock 和synchronized 都是 可重入鎖。

下面是使用實(shí)例:

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

運(yùn)行截圖:

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

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

我們以自旋鎖作為例子,

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

對(duì)于自旋鎖來說,

1、若有同一線程兩調(diào)用lock() ,會(huì)導(dǎo)致第二次調(diào)用lock位置進(jìn)行自旋,產(chǎn)生了死鎖說明這個(gè)鎖并不是可重入的。(在lock函數(shù)內(nèi),應(yīng)驗(yàn)證線程是否為已經(jīng)獲得鎖的線程)

2、若1問題已經(jīng)解決,當(dāng)unlock()第一次調(diào)用時(shí),就已經(jīng)將鎖釋放了。實(shí)際上不應(yīng)釋放鎖。(采用計(jì)數(shù)次進(jìn)行統(tǒng)計(jì))修改之后,如下:

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

該自旋鎖即為可重入鎖。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論