Java同步代碼塊和同步方法原理與應(yīng)用案例詳解
本文實例講述了Java同步代碼塊和同步方法。分享給大家供大家參考,具體如下:
一 點睛
所謂原子性:一段代碼要么執(zhí)行,要么不執(zhí)行,不存在執(zhí)行一部分被中斷的情況。言外之意是這段代碼就像原子一樣,不可拆分。
同步的含義:多線程在代碼執(zhí)行的關(guān)鍵點上,互通消息,相互協(xié)作,共同把任務(wù)正確的完成。
同步代碼塊語法:
synchronized(對象) { 需要同步的代碼塊; }
同步方法語法:
訪問控制符 synchronized 返回值類型方法名稱(參數(shù)) { 需要同步的代碼; }
二 同步代碼塊完成賣票功能
1 代碼
public class threadSynchronization { public static void main( String[] args ) { TestThread t = new TestThread(); // 啟動了四個線程,實現(xiàn)資源共享 new Thread( t ).start(); new Thread( t ).start(); new Thread( t ).start(); new Thread( t ).start(); } } class TestThread implements Runnable { private int tickets = 5; @Override public void run() { while( true ) { synchronized( this ) { if( tickets <= 0 ) break; try { Thread.sleep( 100 ); } catch( Exception e ) { e.printStackTrace(); } System.out.println( Thread.currentThread().getName() + "出售票" + tickets ); tickets -= 1; } } } }
2 運行
Thread-0出售票5
Thread-3出售票4
Thread-3出售票3
Thread-2出售票2
Thread-2出售票1
三 同步方法完成買票功能
1 代碼
public class threadSynchronization { public static void main( String[] args ) { TestThread t = new TestThread(); // 啟動了四個線程,實現(xiàn)資源共享的目的 new Thread( t ).start(); new Thread( t ).start(); new Thread( t ).start(); new Thread( t ).start(); } } class TestThread implements Runnable { private int tickets = 5; public void run() { while( tickets > 0 ) { sale(); } } public synchronized void sale() { if( tickets > 0 ) { try { Thread.sleep( 100 ); } catch( Exception e ) { e.printStackTrace(); } System.out.println( Thread.currentThread().getName() + "出售票" + tickets ); tickets -= 1; } } }
2 運行
Thread-0出售票5
Thread-0出售票4
Thread-3出售票3
Thread-2出售票2
Thread-1出售票1
更多java相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Java進(jìn)程與線程操作技巧總結(jié)》、《Java數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Java操作DOM節(jié)點技巧總結(jié)》、《Java文件與目錄操作技巧匯總》和《Java緩存操作技巧匯總》
希望本文所述對大家java程序設(shè)計有所幫助。
相關(guān)文章
詳解springboot?springsecuroty中的注銷和權(quán)限控制問題
這篇文章主要介紹了springboot-springsecuroty?注銷和權(quán)限控制,賬戶注銷需要在SecurityConfig中加入開啟注銷功能的代碼,權(quán)限控制要導(dǎo)入springsecurity和thymeleaf的整合依賴,本文通過實例代碼給大家介紹的非常詳細(xì),需要的朋友參考下吧2022-03-03MybatisPlus的MetaObjectHandler與@TableLogic使用
這篇文章主要介紹了MybatisPlus的MetaObjectHandler與@TableLogic使用方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-04-04Spring事務(wù)傳播中嵌套調(diào)用實現(xiàn)方法詳細(xì)介紹
Spring事務(wù)的本質(zhì)就是對數(shù)據(jù)庫事務(wù)的支持,沒有數(shù)據(jù)庫事務(wù),Spring是無法提供事務(wù)功能的。Spring只提供統(tǒng)一的事務(wù)管理接口,具體實現(xiàn)都是由數(shù)據(jù)庫自己實現(xiàn)的,Spring會在事務(wù)開始時,根據(jù)當(dāng)前設(shè)置的隔離級別,調(diào)整數(shù)據(jù)庫的隔離級別,由此保持一致2022-11-11