Java synchronized關(guān)鍵字使用方式及特性解析
這篇文章主要介紹了Java synchronized關(guān)鍵字使用方式及特性解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
synchronized 關(guān)鍵字是實現(xiàn)鎖的一種方式,是在jvm層面實現(xiàn)的非公平鎖,以下是使用synchronized的四種方式
synchronized 特性:
1.非公平鎖
2.可重入性
1.作用在方法上,保證了訪問同一個對象的同一個方法的線程同步
public synchronized void testFun(String str){
for(int i=0;i<15;i++){
System.out.println(str+",執(zhí)行中...");
}
}
2.對象加鎖,保證同時訪問同一個對象的線程同步
public void testObject(String str){
synchronized (this){
for(int i=0; i<15;i++){
System.out.println(str+",執(zhí)行中");
}
}
}
1,2 兩種加鎖方式在表現(xiàn)形式上是相同的
public static void main(String[] args){
ExecutorService executorService = Executors.newCachedThreadPool();
SynchronizeTest1 synchronizeTest1 = new SynchronizeTest1();
executorService.execute(new Runnable() {
@Override
public void run() {
synchronizeTest1.testObject("線程1");
}
});
executorService.execute(new Runnable() {
@Override
public void run() {
synchronizeTest1.testObject("線程2");
}
});
}
3.作用在類上
public static void testClass(String str){
synchronized (SynchronizeTest2.class){
for(int i=0 ;i<15;i++){
System.out.println(str+",執(zhí)行中");
}
}
}
4.作用在靜態(tài)方法上
public synchronized static void testStaticFun(String str){
for(int i=0;i<15;i++){
System.out.println(str+",執(zhí)行中");
}
}
3,4 在表現(xiàn)形式上是一樣的
public static void main(String[] args){
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(new Runnable() {
@Override
public void run() {
testClass("線程1"); //可以替換為testStaticFun 方法
}
});
executorService.execute(new Runnable() {
@Override
public void run() {
testClass("線程2"); //可以替換為testStaticFun 方法
}
});
executorService.shutdown();
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
使用@PropertySource讀取配置文件通過@Value進行參數(shù)注入
這篇文章主要介紹了使用@PropertySource讀取配置文件通過@Value進行參數(shù)注入,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03
使用Mybatis-plus策略自動更新數(shù)據(jù)庫時間失敗問題解決
這篇文章主要介紹了使用Mybatis-plus策略自動更新數(shù)據(jù)庫時間失敗問題解決,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10
springboot-dubbo cannot be cast to問題及解決
這篇文章主要介紹了springboot-dubbo cannot be cast to問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-04-04
關(guān)于springboot中nacos動態(tài)路由的配置
這篇文章主要介紹了springboot中nacos動態(tài)路由的配置方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-09-09
springboot實現(xiàn)獲取客戶端IP地址的示例代碼
本文介紹了在SpringBoot中獲取客戶端IP地址的幾種方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-11-11
Spring+Mybatis 實現(xiàn)aop數(shù)據(jù)庫讀寫分離與多數(shù)據(jù)庫源配置操作
這篇文章主要介紹了Spring+Mybatis 實現(xiàn)aop數(shù)據(jù)庫讀寫分離與多數(shù)據(jù)庫源配置操作,需要的朋友可以參考下2017-09-09

