多執行緒 三 關於鎖的8個問題

2021-10-08 18:57:32 字數 3946 閱讀 8367

使用synchronized鎖

先發簡訊後打**

原因

synchronized鎖的物件是方法的呼叫者,test1的物件都是phone,因為用的同一把鎖,所以誰先拿到誰先執行。

public

synchronized

void

sendsms()

catch

(interruptedexception e)

system.out.

println

("發簡訊");

}

結果依舊是先發簡訊後打**

原因

不能解釋為a先執行所以先發簡訊,依舊要圍繞鎖的原因

public

class

test2

,"a").

start()

;try

catch

(interruptedexception e)

newthread((

)->

,"b").

start()

;}}class

phone2

catch

(interruptedexception e)

system.out.

println

("發簡訊");

}public

synchronized

void

call()

//沒有鎖,不是同步方法

public

void

hello()

}

結果hello先執行

原因

synchronized鎖的物件是方法的呼叫者,因為hello()方法沒有加鎖,不需要等待鎖。

public

class

test2

,"a").

start()

;try

catch

(interruptedexception e)

newthread((

)->

,"b").

start()

;}}class

phone2

catch

(interruptedexception e)

system.out.

println

("發簡訊");

}public

synchronized

void

call()

//沒有鎖,不是同步方法

原因synchronized鎖的物件是方法的呼叫者,此時我們有兩個物件,phone1和phone2,兩者互不影響,又因為發簡訊的方法延遲了4秒,所以打**先執行(這講的有點像高中解數學題了額)。

class

phone3

catch

(interruptedexception e)

system.out.

println

("發簡訊");

}public

static

synchronized

void

call()

}

結果先發簡訊,後打**

原因

前提:synchronized鎖的物件是方法的呼叫者,因為用的同一把鎖,所以誰先拿到誰先執行

推導:static是靜態,類一載入就有了,鎖的是class,所以依舊是a先拿到先執行發簡訊

public

class

test3

,"a").

start()

;try

catch

(interruptedexception e)

newthread((

)->

,"b").

start()

;}}class

phone3

catch

(interruptedexception e)

system.out.

println

("發簡訊");

}public

static

synchronized

void

call()

}

結果

原因

雖然這裡有兩個物件,但因為都是static靜態方法,所以他們的真正物件都是一樣的,其實都是同乙個class物件—》phone3的class全域性唯一

class

phone4

catch

(interruptedexception e)

system.out.

println

("發簡訊");

}//普通同步方法

public

synchronized

void

call()

}

結果先打**後發簡訊

原因

乙個靜態同步方法,乙個普通同步方法,兩個鎖的物件不一樣,發簡訊有4秒延遲。

public

class

test4

,"a").

start()

;try

catch

(interruptedexception e)

newthread((

)->

,"b").

start()

;}}class

phone4

catch

(interruptedexception e)

system.out.

println

("發簡訊");

}//普通同步方法

public

synchronized

void

call()

//沒有鎖,不是同步方法

public

void

hello()

}

結果

原因

這裡不說大家應該也明白了。

8鎖,就是關於鎖的8個問題

class phone public synchronized void call class test,a start 捕獲 try catch interruptedexception e new thread b start 兩個方法用的是同乙個鎖,排隊執行 class phone catch...

多執行緒鎖的問題

public class synctest start new thread new runnable start class a catch interruptedexception e system.out.println i public void f2 catch interruptedex...

關於執行緒鎖的乙個問題

public class tt implements runnable public void m2 throws exception public void run catch exception e public static void main string args throws excep...