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)文章
使用dubbo+zookeeper+spring boot構(gòu)建服務(wù)的方法詳解
這篇文章主要給大家介紹了關(guān)于如何使用dubbo+zookeeper+spring boot構(gòu)建服務(wù)的相關(guān)資料,文中通過示例代碼及圖片介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-05-05SpringBoot整合mysql、postgres及sqlserver實現(xiàn)多數(shù)據(jù)源配置實戰(zhàn)案例
在工作中業(yè)務(wù)的發(fā)展或業(yè)務(wù)數(shù)據(jù)隔離的場景下,通常需要一個項目中引入多個數(shù)據(jù)源,但SpringBoot默認(rèn)的自動化配置是單數(shù)據(jù)源的,這篇文章主要給大家介紹了關(guān)于SpringBoot整合mysql、postgres及sqlserver實現(xiàn)多數(shù)據(jù)源配置的相關(guān)資料,需要的朋友可以參考下2023-12-12Spring Security實現(xiàn)自定義訪問策略
本文介紹Spring Security實現(xiàn)自定義訪問策略,當(dāng)根據(jù)誰訪問哪個域?qū)ο笞龀霭踩珱Q策時,您可能需要一個自定義的訪問決策投票者,幸運的是,Spring Security有很多這樣的選項來實現(xiàn)訪問控制列表(ACL)約束,下面就來學(xué)習(xí)Spring Security自定義訪問策略,需要的朋友可以參考下2022-02-02微信公眾號支付(二)實現(xiàn)統(tǒng)一下單接口
本篇文章主要給大家介紹調(diào)用微信公眾支付的統(tǒng)一下單API,通過參數(shù)封裝為xml格式并發(fā)送到微信給的接口地址就可以獲得返回內(nèi)容,需要的朋友可以參考下本文2015-09-09