Java同步代碼塊和同步方法原理與應用案例詳解
本文實例講述了Java同步代碼塊和同步方法。分享給大家供大家參考,具體如下:
一 點睛
所謂原子性:一段代碼要么執(zhí)行,要么不執(zhí)行,不存在執(zhí)行一部分被中斷的情況。言外之意是這段代碼就像原子一樣,不可拆分。
同步的含義:多線程在代碼執(zhí)行的關鍵點上,互通消息,相互協作,共同把任務正確的完成。
同步代碼塊語法:
synchronized(對象) { 需要同步的代碼塊; }
同步方法語法:
訪問控制符 synchronized 返回值類型方法名稱(參數) { 需要同步的代碼; }
二 同步代碼塊完成賣票功能
1 代碼
public class threadSynchronization { public static void main( String[] args ) { TestThread t = new TestThread(); // 啟動了四個線程,實現資源共享 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(); // 啟動了四個線程,實現資源共享的目的 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相關內容感興趣的讀者可查看本站專題:《Java進程與線程操作技巧總結》、《Java數據結構與算法教程》、《Java操作DOM節(jié)點技巧總結》、《Java文件與目錄操作技巧匯總》和《Java緩存操作技巧匯總》
希望本文所述對大家java程序設計有所幫助。
相關文章
詳解springboot?springsecuroty中的注銷和權限控制問題
這篇文章主要介紹了springboot-springsecuroty?注銷和權限控制,賬戶注銷需要在SecurityConfig中加入開啟注銷功能的代碼,權限控制要導入springsecurity和thymeleaf的整合依賴,本文通過實例代碼給大家介紹的非常詳細,需要的朋友參考下吧2022-03-03MybatisPlus的MetaObjectHandler與@TableLogic使用
這篇文章主要介紹了MybatisPlus的MetaObjectHandler與@TableLogic使用方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-04-04