使用synchronized實作一個Lock程式碼詳解
本文要為大家介紹如何使用synchronized實作Lock程式碼,以下是實戰案例,需要的朋友可以參考借鏡。
方式一:
public synchronized void a(){ //TODO }
方式二:
public void b(){ synchronized(this){ //TODO } }
從這兩種方式來你看,鎖都是加在{}之間的,我們再來看看Lock是如何做的呢:
public void c() { lock.lock(); try { // TODO } finally { lock.unlock(); } }
這種方式的鎖是加在lock( )和unlock()之間的,所以要實作一個lock功能,就要想怎麼實作這樣兩個方法,lock()和unlock()方法,先定義一個框架如下:
public void lock(){ } public void unlock(){ }
然後要想怎麼用synchronized去實作這兩個方法。
現在其實只是稍微清楚了一點思路,但是還不知道怎麼去填充這兩個方法,這是後再來分析一下Lock的加鎖有什麼特點,再來看看這段程式碼:
public void c() { lock.lock(); //When current thread get the lock, other thread has to wait try { //current thread get in the lock, other thread can not get in // TODO } finally { lock.unlock(); //current thread release the lock } }
這段程式碼我只是加了一點註釋,別的什麼都沒有做,是不是幫忙理解這段程式碼,看看出現頻率最高的字是什麼,是currentthread,那我們去填充lock()和unlock()方法的時候是不是注意到要抓住currentthread這個關鍵字就可以找到解決方案呢?答案是肯定的。
接著分析,使用synchronized的時候該如何讓執行緒等待呢?是用wait()方法。怎麼讓執行緒喚醒呢,是用notify()方法。那麼就要在lock()方法中使用wait()方法,在unlock()方法中使用notify()方法。那我們在使用wait()和notify()的時候是有一個條件的,想想我們應該用什麼作為條件呢?
我們應該使用當前鎖是否被佔用作為判斷條件,如果鎖被佔用,currentthread等待,想想我們在使用synchronized的時候是不是一直使用的這個條件,答案也是肯定的。
再來分析什麼時候釋放鎖,使用什麼作為條件,想想如果線程A拿到了鎖,線程B能釋放嗎?當然不能,如果B能釋放就違反了原則,當然不能。肯定是A線程的鎖只能A來釋放。所以判斷條件就是判斷持有鎖的執行緒是不是currentthread,如果是的話,可以釋放,不是的話當然不能。
現在來看看完整的程式碼:
package test.lock; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; public class NaiveLock { private static final long NONE = -1; private long owner = NONE; private Boolean isLooked() { return owner != NONE; } public synchronized void lock() { long currentThreadId = Thread.currentThread().getId(); if (owner == currentThreadId) { throw new IllegalStateException("Lock has been acquired by current thread"); } while (this.isLooked()) { System.out.println(String.format("thread %s is waitting lock", currentThreadId)); try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } owner = currentThreadId; System.out.println(String.format("Lock is acquired by thread %s", owner)); } public synchronized void unlock() { if (!this.isLooked() || owner != Thread.currentThread().getId()) { throw new IllegalStateException("Only Lock owner can unlock the lock"); } System.out.println(String.format("thread %s is unlocking", owner)); System.out.println(); owner = NONE; notify(); } public static void main(String[] args) { final NaiveLock lock = new NaiveLock(); ExecutorService executor = Executors.newFixedThreadPool(20, new ThreadFactory() { private ThreadGroup group = new ThreadGroup("test thread group"); { group.setDaemon(true); } @Override public Thread newThread(Runnable r) { return new Thread(group, r); } } ); for (int i = 0; i < 20; i++) { executor.submit(new Runnable() { @Override public void run() { lock.lock(); System.out.println(String.format("thread %s is running...", Thread.currentThread().getId())); try { Thread.sleep(new Random().nextint(1000)); } catch (InterruptedException e) { e.printStackTrace(); } lock.unlock(); } } ); } } }
#執行一下看看結果:
Lock is acquired by thread 8 thread 8 is running... thread 27 is waitting lock thread 26 is waitting lock thread 25 is waitting lock thread 24 is waitting lock thread 23 is waitting lock thread 22 is waitting lock thread 21 is waitting lock thread 20 is waitting lock thread 19 is waitting lock thread 18 is waitting lock thread 17 is waitting lock thread 16 is waitting lock thread 15 is waitting lock thread 14 is waitting lock thread 13 is waitting lock thread 12 is waitting lock thread 11 is waitting lock thread 10 is waitting lock thread 9 is waitting lock thread 8 is unlocking Lock is acquired by thread 27 thread 27 is running... thread 27 is unlocking Lock is acquired by thread 26 thread 26 is running... thread 26 is unlocking Lock is acquired by thread 25 thread 25 is running... thread 25 is unlocking Lock is acquired by thread 24 thread 24 is running... thread 24 is unlocking Lock is acquired by thread 23 thread 23 is running... thread 23 is unlocking Lock is acquired by thread 22 thread 22 is running... thread 22 is unlocking Lock is acquired by thread 21 thread 21 is running... thread 21 is unlocking Lock is acquired by thread 20 thread 20 is running... thread 20 is unlocking Lock is acquired by thread 19 thread 19 is running... thread 19 is unlocking Lock is acquired by thread 18 thread 18 is running... thread 18 is unlocking Lock is acquired by thread 17 thread 17 is running... thread 17 is unlocking Lock is acquired by thread 16 thread 16 is running... thread 16 is unlocking Lock is acquired by thread 15 thread 15 is running... thread 15 is unlocking Lock is acquired by thread 14 thread 14 is running... thread 14 is unlocking Lock is acquired by thread 13 thread 13 is running... thread 13 is unlocking Lock is acquired by thread 12 thread 12 is running... thread 12 is unlocking Lock is acquired by thread 11 thread 11 is running... thread 11 is unlocking Lock is acquired by thread 10 thread 10 is running... thread 10 is unlocking Lock is acquired by thread 9 thread 9 is running... thread 9 is unlocking
如果把for循環改成30次,再看一下結果:
Lock is acquired by thread 8 thread 8 is running... thread 27 is waitting lock thread 26 is waitting lock thread 25 is waitting lock thread 24 is waitting lock thread 23 is waitting lock thread 22 is waitting lock thread 21 is waitting lock thread 20 is waitting lock thread 19 is waitting lock thread 18 is waitting lock thread 17 is waitting lock thread 16 is waitting lock thread 15 is waitting lock thread 14 is waitting lock thread 13 is waitting lock thread 12 is waitting lock thread 11 is waitting lock thread 10 is waitting lock thread 9 is waitting lock thread 8 is unlocking Lock is acquired by thread 27 thread 27 is running... thread 8 is waitting lock thread 27 is unlocking Lock is acquired by thread 27 thread 27 is running... thread 26 is waitting lock thread 27 is unlocking Lock is acquired by thread 27 thread 27 is running... thread 25 is waitting lock thread 27 is unlocking Lock is acquired by thread 24 thread 24 is running... thread 27 is waitting lock thread 24 is unlocking Lock is acquired by thread 23 thread 23 is running... thread 24 is waitting lock thread 23 is unlocking Lock is acquired by thread 22 thread 22 is running... thread 23 is waitting lock thread 22 is unlocking Lock is acquired by thread 22 thread 22 is running... thread 21 is waitting lock thread 22 is unlocking Lock is acquired by thread 22 thread 22 is running... thread 20 is waitting lock thread 22 is unlocking Lock is acquired by thread 22 thread 22 is running... thread 19 is waitting lock thread 22 is unlocking Lock is acquired by thread 22 thread 22 is running... thread 18 is waitting lock thread 22 is unlocking Lock is acquired by thread 17 thread 17 is running... thread 17 is unlocking Lock is acquired by thread 16 thread 16 is running... thread 16 is unlocking Lock is acquired by thread 15 thread 15 is running... thread 15 is unlocking Lock is acquired by thread 14 thread 14 is running... thread 14 is unlocking Lock is acquired by thread 13 thread 13 is running... thread 13 is unlocking Lock is acquired by thread 12 thread 12 is running... thread 12 is unlocking Lock is acquired by thread 11 thread 11 is running... thread 11 is unlocking Lock is acquired by thread 10 thread 10 is running... thread 10 is unlocking Lock is acquired by thread 9 thread 9 is running... thread 9 is unlocking Lock is acquired by thread 8 thread 8 is running... thread 8 is unlocking Lock is acquired by thread 26 thread 26 is running... thread 26 is unlocking Lock is acquired by thread 25 thread 25 is running... thread 25 is unlocking Lock is acquired by thread 27 thread 27 is running... thread 27 is unlocking Lock is acquired by thread 24 thread 24 is running... thread 24 is unlocking Lock is acquired by thread 23 thread 23 is running... thread 23 is unlocking Lock is acquired by thread 21 thread 21 is running... thread 21 is unlocking Lock is acquired by thread 20 thread 20 is running... thread 20 is unlocking Lock is acquired by thread 19 thread 19 is running... thread 19 is unlocking Lock is acquired by thread 18 thread 18 is running... thread 18 is unlocking
相信看了這些案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!
相關讀取:
php如何實作堆疊資料結構以及括號匹配演算法的程式碼範例詳解
php中最簡單的字串匹配演算法,php匹配演算法_PHP教程
以上是使用synchronized實作一個Lock程式碼詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

一、基本特性1.一開始是樂觀鎖,如果鎖衝突頻繁,就轉換為悲觀鎖.2.開始是輕量級鎖實現,如果鎖被持有的時間較長,就轉換成重量級鎖. 3.實現輕量級鎖的時候大概率用到的自旋鎖策略4.是一種不公平鎖5.是一種可重入鎖6.不是讀寫鎖二、加鎖工作過程JVM將synchronized鎖分為無鎖、偏向鎖、輕量級鎖、重量級鎖狀態。會根據情況,進行依序升級。偏向鎖假設男主角是一個鎖,女主角是一個線程.如果只有這一個線程來使用這個鎖,那麼男主女主即使不領證結婚(避免了高成本操作),也可以一直幸福的生活下去.但是女配出現

Jdk1.5以後,在java.util.concurrent.locks套件下,有一組實現線程同步的介面和類,說到線程的同步,可能大家都會想到synchronized關鍵字,這是java內建的關鍵字,用來處理線程同步的,但這個關鍵字有很多的缺陷,使用起來也不是很方便和直觀,所以就出現了Lock,下面,我們就來對比著講解Lock。通常我們在使用synchronized關鍵字的時候會遇到下面這些問題:(1)不可控性,無法做到隨心所欲的加鎖和釋放鎖。 (2)效率比較低下,例如我們現在並發的讀兩個文件,讀與讀之

1.作用(1)Lock方式來獲取鎖支援中斷、超時不獲取、是非阻塞的(2)提高了語義化,哪裡加鎖,哪裡解鎖都得寫出來(3)Lock顯式鎖可以給我們帶來很好的靈活性,但同時我們必須手動釋放鎖定(4)支援Condition條件物件(5)允許多個讀取線程同時存取共享資源2.lock用法//獲取鎖定voidlock()//如果當前線程未中斷,則取得鎖定voidlockInterruptibly()//傳回綁定至此Lock實例的新Condition實例ConditionnewCondition()//僅在呼叫時鎖定

說明1、Lock是java.util.concurent套件下的接口,定義了一系列的鎖定操作方法。 2.Lock介面主要包括ReentrantLock、ReentrantReadWriteLock、ReentrantReadWriteLock、WriteLock實作類別。與Synchronized不同,Lock提供了取得鎖定、釋放鎖定等相關介面,使其使用更加靈活,操作更加複雜。實例ReentrantReadWriteLocklock=newReentrantReadWriteLock();Lockread

一、Java中鎖的概念自旋鎖:是指當一個線程獲取鎖的時候,如果鎖已經被其它線程獲取,那麼該線程將循環等待,然後不斷的判斷鎖是否能被成功獲取,直到獲取到鎖才會退出循環。樂觀鎖:假定沒有衝突,在修改數據時如果發現數據和先前取得的不一致,則讀最新數據,重試修改。悲觀鎖:假定會發生並發衝突,同步所有對資料的相關操作,從讀取資料就開始上鎖。獨享鎖(寫):給資源加上寫鎖,執行緒可以修改資源,其它執行緒不能再加鎖(單一寫)。共享鎖(讀):給資源加上讀鎖後只能讀不能修改,其它執行緒也只能加讀鎖,不能加寫鎖(多度)。看成S

Java的synchronized使用方法總結1.把synchronized當作函數修飾符時,範例程式碼如下:Publicsynchronizedvoidmethod(){//….}這也就是同步方法,那這時synchronized鎖定的是哪個物件呢?他鎖定的是呼叫這個同步方法物件。也就是說,當一個物件P1在不同的執行緒中執行這個同步方法時,他們之間會形成互斥,達到同步的效果。但是這個物件所屬的Class所產生的另一物件P2卻能夠任意呼叫這個被加了synchronized關鍵字的方法。上邊的範例程式碼等

1.說明synchronized算是我們最常用的同步方式,主要有三種使用方式。 2.實例//普通類別方法同步synchronizedpublidvoidinvoke(){}//類別靜態方法同步synchronizedpublicstaticvoidinvoke(){}//程式碼區塊同步synchronized(object){}這三種方式的不同之處在於同步的物件不同,普通類別synchronized同步的是物件本身,靜態方法同步的是類別Class本身,程式碼區塊同步的是我們在括號內部填入的物件。 Java有哪些集合

工具準備在正式談synchronized的原理之前我們先談一下自旋鎖,因為在synchronized的優化當中自旋鎖發揮了很大的作用。而需要了解自旋鎖,我們首先要了解什麼是原子性。所謂原子性簡單說來就是一個一個操作要么不做要么全做,全做的意思就是在操作的過程當中不能夠被中斷,比如說對變量data進行加一操作,有以下三個步驟:將data從記憶體載入到暫存器。將data這個值加一。將得到的結果寫回記憶體。原子性就表示一個執行緒在進行加一操作的時候,不能夠被其他執行緒中斷,只有這個執行緒執行完這三個過程的時候
