synchronized的鎖問題

2022-08-15 19:54:16 字數 865 閱讀 5735

題描述

有乙個類a,提供了三個方法。分別是靜態同步方法,非靜態同步方法,含有靜態**塊的方法

class

a

public

synchronized

void

print2()

public

void

print3()

}private

static

void

print()

}}

四種情況的輸出結果

class

test

//2.兩個執行緒,同乙個物件,呼叫非靜態同步方法print2

@test

public

void

test2()

//3.兩個執行緒,不同物件,呼叫非靜態同步方法print2

@test

public

void

test3()

//4.兩個執行緒,同乙個物件,呼叫普通非靜態方法(帶有同步**塊)print3

@test

public

void

test4()

}

問題答案

先直接報上答案:

一直輸出「thread-1」

一直輸出「thread-1」

交替輸出「thread-1」和「thread-2」

交替輸出「thread-1」和「thread-2」

問題本質分析

不廢話,直接點出,這四個問題只要明白兩件事即可:

所以所以

synchronized 鎖的重入

1 乙個同步方法呼叫另外乙個同步方法,能否得到鎖?重入 synchronized預設支援重入 slf4j topic test public class demo catch interruptedexception e test2 為什麼test2還需要加sync 他本身就包含在test1 而te...

synchronized 修飾的鎖

datetime 2020 11 25 21 14 author db public class concurrency private static void lockcode private static void lockmethod 鎖的是物件例項方法,同一物件是同步的,不同物件是非同步的 ...

synchronized鎖的公升級

在分析markword時,提到了偏向鎖 輕量級鎖 重量級鎖。在分析這幾種鎖的區別時,我們先來思考乙個問題 使用鎖能夠實現資料的安全性,但是會帶來效能的下降。不使用鎖能夠基於執行緒並行提公升程式效能,但是卻不能保證執行緒安全性。這兩者之間似乎是沒有辦法達到既能滿足效能也能滿足安全性的要求。hotspo...