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

Java鎖之可重入鎖介紹

 更新時(shí)間:2014年11月12日 08:58:32   投稿:junjie  
這篇文章主要介紹了Java鎖之可重入鎖介紹,可重入鎖,也叫做遞歸鎖,指的是同一線程外層函數(shù)獲得鎖之后,內(nèi)層遞歸函數(shù)仍然有獲取該鎖的代碼,但不受影響,需要的朋友可以參考下

鎖作為并發(fā)共享數(shù)據(jù),保證一致性的工具,在JAVA平臺(tái)有多種實(shí)現(xiàn)(如 synchronized 和 ReentrantLock等等 ) 。這些已經(jīng)寫(xiě)好提供的鎖為我們開(kāi)發(fā)提供了便利,但是鎖的具體性質(zhì)以及類(lèi)型卻很少被提及。本系列文章將分析JAVA下常見(jiàn)的鎖名稱(chēng)以及特性,為大家答疑解惑。

四、可重入鎖:

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

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

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

復(fù)制代碼 代碼如下:

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

兩個(gè)例子最后的結(jié)果都是正確的,即 同一個(gè)線程id被連續(xù)輸出兩次。

結(jié)果如下:

復(fù)制代碼 代碼如下:

Threadid: 8
Threadid: 8
Threadid: 10
Threadid: 10
Threadid: 9
Threadid: 9

可重入鎖最大的作用是避免死鎖。
我們以自旋鎖作為例子。

復(fù)制代碼 代碼如下:

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ì)于自旋鎖來(lái)說(shuō):

1、若有同一線程兩調(diào)用lock() ,會(huì)導(dǎo)致第二次調(diào)用lock位置進(jìn)行自旋,產(chǎn)生了死鎖
說(shuō)明這個(gè)鎖并不是可重入的。(在lock函數(shù)內(nèi),應(yīng)驗(yàn)證線程是否為已經(jīng)獲得鎖的線程)
2、若1問(wèn)題已經(jīng)解決,當(dāng)unlock()第一次調(diào)用時(shí),就已經(jīng)將鎖釋放了。實(shí)際上不應(yīng)釋放鎖。
(采用計(jì)數(shù)次進(jìn)行統(tǒng)計(jì))

修改之后,如下:

復(fù)制代碼 代碼如下:

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

  }

 }
}

該自旋鎖即為可重入鎖。

相關(guān)文章

最新評(píng)論