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?@Validated的概念及示例實戰(zhàn)
這篇文章主要介紹了springboot?@Validated的概念以及實戰(zhàn),使用?@Validated?注解,Spring?Boot?應(yīng)用可以有效地實現(xiàn)輸入驗證,提高數(shù)據(jù)的準(zhǔn)確性和應(yīng)用的安全性,本文結(jié)合實例給大家講解的非常詳細(xì),需要的朋友可以參考下2024-04-04
基于SpringCloudAlibaba+Skywalking的全鏈路監(jiān)控設(shè)計方案
這篇文章主要介紹了基于SpringCloudAlibaba+Skywalking的全鏈路監(jiān)控設(shè)計方案,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2024-01-01
SpringBoot中Mybatis注解一對多和多對多查詢實現(xiàn)示例
這篇文章主要介紹了SpringBoot中Mybatis注解一對多和多對多查詢的實現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-03-03
Java中的BufferedInputStream與BufferedOutputStream使用示例
BufferedInputStream和BufferedOutputStream分別繼承于FilterInputStream和FilterOutputStream,代表著緩沖區(qū)的輸入輸出,這里我們就來看一下Java中的BufferedInputStream與BufferedOutputStream使用示例:2016-06-06
淺談Java中Lambda表達(dá)式的相關(guān)操作
java8新特性,Lambda是一個匿名函數(shù),類似Python中的Lambda表達(dá)式、js中的箭頭函數(shù),目的簡化操作,文中有非常詳細(xì)的介紹及代碼示例,需要的朋友可以參考下2021-06-06

