同步鎖的作用範圍

2021-10-04 17:21:06 字數 2638 閱讀 7314

synchronized 解決的三種方式:

1)使用synchronized **塊

2)synchronized 同步方法

3)synchronized 同步靜態

使用synchronize**塊通過指定鎖來制定作用範圍 :

1. 以this充當鎖 是以物件作為鎖 鎖整個物件

2. 以x.class 作為鎖 是以整個類為鎖 鎖此類的所有物件

使用 synchronized 同步(靜態)方法 有幾種不同的情況
1. 普通方法與同步(包括靜態)方法互補相關

2. synchronized 方法預設以this為鎖 也就是鎖整個物件

3. synchronized 靜態方法預設以class為鎖 也就是鎖整個類

4. 同步靜態方法與普通同步方法之間互不干擾 (記憶體區域不同)

同一物件普通同步方法

執行結果是 先等待3s後再輸出 說明鎖了整個物件

//測試方法

public

static

void

main

(string[

] args)

throws interruptedexception

catch

(interruptedexception e)})

.start()

; thread.

sleep

(1000);

newthread((

)->

catch

(exception e)})

.start()

;}//普通的synchronized鎖物件 呼叫方法是將整個物件鎖住 相當於將兩個方法縮到了一起

//靜態鎖鎖的是類 (不同物件之間也會鎖住)

class

testnomalsynchronize

public

synchronized

void

test2()

}

不同物件普通同步方法

執行結果 : 先輸出test2 過2s輸出test1 說明不同物件間沒有同步

public

static

void

main

(string[

] args)

throws interruptedexception

catch

(interruptedexception e)})

.start()

; thread.

sleep

(1000);

newthread((

)->

catch

(exception e)})

.start()

;}

同乙個(不同)物件的靜態同步方法和普通同步方法 (是不是同乙個物件對靜態方法不影響)

執行結果 : 先輸出test2 過2s輸出test1 說明靜態同步方法和普通同步方法間沒有同步

public

static

void

main

(string[

] args)

throws interruptedexception

catch

(interruptedexception e)})

.start()

; thread.

sleep

(1000);

newthread((

)->

catch

(exception e)})

.start()

;}class

teststaticsynchronize

public

synchronized

void

test2()

}class

teststaticsynchronize1

public

synchronized

void

test2()

public

synchronized

static

void

test3()

throws interruptedexception

}

同乙個(不同)物件的兩個靜態方法

執行結果 : 等待3s 執行test1和test2 說明兩個靜態方法之間是同步的

public

static

void

main

(string[

] args)

throws interruptedexception

catch

(interruptedexception e)})

.start()

; thread.

sleep

(1000);

newthread((

)->

catch

(exception e)})

.start()

;}

go中鎖的作用範圍

網上介紹sync.mutex的文章已經很多了,這裡也不深提。具體就兩種,乙個互斥鎖sync.mutex 乙個讀寫鎖sync.rwmutex。兩種鎖都有兩個方法 lock 和unlock 互斥鎖就是,其他執行緒不能讀也不能寫 讀寫鎖就是,其他執行緒可以讀但是不能寫。但是由於網上的例子大多形式為 var...

事務的範圍和鎖範圍

transactional rollbackfor exception.class public synchronized void isertuser4 user user 可以看到,因為要考慮併發問題,我在業務層 的方法上加了個 synchronized 關鍵字。我舉個實際 的場景,比如乙個資料...

Spring Bean的作用域(作用範圍)

文章目錄 scope 1.註解方式配置 1.1 測試singleton 1.2 測試prototype 2.xml方式配置在spring中使用 scope來表示乙個bean定義對應產生例項的型別,也可以說是對應例項的作用範圍。spring中 指定scope的方法分以下兩種 採用xml配置方式時,可以...