java實(shí)現(xiàn)同步的幾種方式(示例詳解)
1.同步方法
即有synchronized關(guān)鍵字修飾的方法。
由于java的每個(gè)對象都有一個(gè)內(nèi)置鎖,當(dāng)用此關(guān)鍵字修飾方法時(shí),
內(nèi)置鎖會保護(hù)整個(gè)方法。在調(diào)用該方法前,需要獲得內(nèi)置鎖,否則就處于阻塞狀態(tài)。
代碼如:
public synchronized void save(){}
注: synchronized關(guān)鍵字也可以修飾靜態(tài)方法,此時(shí)如果調(diào)用該靜態(tài)方法,將會鎖住整個(gè)類
public class Bank {
private int count =0;//賬戶余額
//存錢
public synchronized void addMoney(int money){
count +=money;
System.out.println(System.currentTimeMillis()+"存進(jìn):"+money);
}
//取錢
public synchronized void subMoney(int money){
if(count-money < 0){
System.out.println("余額不足");
return;
}
count -=money;
System.out.println(+System.currentTimeMillis()+"取出:"+money);
}
//查詢
public void lookMoney(){
System.out.println("賬戶余額:"+count);
}
}2.同步代碼塊
即有synchronized關(guān)鍵字修飾的語句塊。
被該關(guān)鍵字修飾的語句塊會自動被加上內(nèi)置鎖,從而實(shí)現(xiàn)同步
代碼如:
synchronized(object){
}
注:同步是一種高開銷的操作,因此應(yīng)該盡量減少同步的內(nèi)容。
通常沒有必要同步整個(gè)方法,使用synchronized代碼塊同步關(guān)鍵代碼即可。
public class Bank {
private int count =0;//賬戶余額
//存錢
public void addMoney(int money){
synchronized (this) {
count +=money;
}
System.out.println(System.currentTimeMillis()+"存進(jìn):"+money);
}
//取錢
public void subMoney(int money){
synchronized (this) {
if(count-money < 0){
System.out.println("余額不足");
return;
}
count -=money;
}
System.out.println(+System.currentTimeMillis()+"取出:"+money);
}
//查詢
public void lookMoney(){
System.out.println("賬戶余額:"+count);
}
}這樣也實(shí)現(xiàn)了線程同步,運(yùn)行效率上來說也比方法同步效率高,同步是一種高開銷的操作,因此應(yīng)該盡量減少同步的內(nèi)容。通常沒有必要同步整個(gè)方法,使用synchronized代碼塊同步關(guān)鍵代碼即可。。
3.使用特殊域變量(volatile)實(shí)現(xiàn)線程同步
a.volatile關(guān)鍵字為域變量的訪問提供了一種免鎖機(jī)制,
b.使用volatile修飾域相當(dāng)于告訴虛擬機(jī)該域可能會被其他線程更新,
c.因此每次使用該域就要重新計(jì)算,而不是使用寄存器中的值
d.volatile不會提供任何原子操作,它也不能用來修飾final類型的變量
Bank.java代碼如下:
package com.thread.demo;
/**
* Created by HJS on 2017/8/12.
*/
public class Bank {
private volatile int count =0;//賬戶余額
//存錢
public void addMoney(int money){
synchronized (this) {
count +=money;
}
System.out.println(System.currentTimeMillis()+"存進(jìn):"+money);
}
//取錢
public void subMoney(int money){
synchronized (this) {
if(count-money < 0){
System.out.println("余額不足");
return;
}
count -=money;
}
System.out.println(+System.currentTimeMillis()+"取出:"+money);
}
//查詢
public void lookMoney(){
System.out.println("賬戶余額:"+count);
}
}此時(shí),順序又亂了,說明同步又出現(xiàn)了問題,因?yàn)関olatile不能保證原子操作導(dǎo)致的,因此volatile不能代替synchronized。此外volatile會組織編譯器對代碼優(yōu)化,因此能不使用它就不適用它吧。它的原理是每次要線程要訪問volatile修飾的變量時(shí)都是從內(nèi)存中讀取,而不是存緩存當(dāng)中讀取,因此每個(gè)線程訪問到的變量值都是一樣的。這樣就保證了同步。
4.使用重入鎖實(shí)現(xiàn)線程同步
在JavaSE5.0中新增了一個(gè)java.util.concurrent包來支持同步。ReentrantLock類是可重入、互斥、實(shí)現(xiàn)了Lock接口的鎖, 它與使用synchronized方法和快具有相同的基本行為和語義,并且擴(kuò)展了其能力。
ReenreantLock類的常用方法有:
ReentrantLock() : 創(chuàng)建一個(gè)ReentrantLock實(shí)例
lock() : 獲得鎖
unlock() : 釋放鎖
注:ReentrantLock()還有一個(gè)可以創(chuàng)建公平鎖的構(gòu)造方法,但由于能大幅度降低程序運(yùn)行效率,不推薦使用
Bank.java代碼修改如下:
public class Bank {
private int count = 0;// 賬戶余額
//需要聲明這個(gè)鎖
private Lock lock = new ReentrantLock();
// 存錢
public void addMoney(int money) {
lock.lock();//上鎖
try{
count += money;
System.out.println(System.currentTimeMillis() + "存進(jìn):" + money);
}finally{
lock.unlock();//解鎖
}
}
// 取錢
public void subMoney(int money) {
lock.lock();
try{
if (count - money < 0) {
System.out.println("余額不足");
return;
}
count -= money;
System.out.println(+System.currentTimeMillis() + "取出:" + money);
}finally{
lock.unlock();
}
}
// 查詢
public void lookMoney() {
System.out.println("賬戶余額:" + count);
}
}注:關(guān)于Lock對象和synchronized關(guān)鍵字的選擇:
a.最好兩個(gè)都不用,使用一種java.util.concurrent包提供的機(jī)制,
能夠幫助用戶處理所有與鎖相關(guān)的代碼。
b.如果synchronized關(guān)鍵字能滿足用戶的需求,就用synchronized,因?yàn)樗芎喕a
c.如果需要更高級的功能,就用ReentrantLock類,此時(shí)要注意及時(shí)釋放鎖,否則會出現(xiàn)死鎖,通常在finally代碼釋放鎖 。
到此這篇關(guān)于java實(shí)現(xiàn)同步的幾種方式的文章就介紹到這了,更多相關(guān)java實(shí)現(xiàn)同步內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Spring Data Neo4j實(shí)現(xiàn)復(fù)雜查詢的多種方式
在 Spring Data Neo4j 中,實(shí)現(xiàn)復(fù)雜查詢可以通過多種方式進(jìn)行,包括使用自定義查詢、方法命名查詢以及使用 Cypher 查詢語言,以下是詳細(xì)介紹,幫助你在 Spring Data Neo4j 中實(shí)現(xiàn)復(fù)雜查詢,需要的朋友可以參考下2024-11-11
Java中new關(guān)鍵字和newInstance方法的區(qū)別分享
在初始化一個(gè)類,生成一個(gè)實(shí)例的時(shí)候,newInstance()方法和new關(guān)鍵字除了一個(gè)是方法一個(gè)是關(guān)鍵字外,最主要的區(qū)別是創(chuàng)建對象的方式不同2013-07-07
深入理解 CAS 算法原理已經(jīng)在jdk中的運(yùn)用
這篇文章主要介紹了深入理解 CAS 算法原理已經(jīng)在jdk中的運(yùn)用,幫助大家更好的使用Java,感興趣的朋友可以了解下2020-12-12
Struts2中validate數(shù)據(jù)校驗(yàn)的兩種方法詳解附Struts2常用校驗(yàn)器
這篇文章主要介紹了Struts2中validate數(shù)據(jù)校驗(yàn)的兩種方法及Struts2常用校驗(yàn)器,本文介紹的非常詳細(xì),具有參考借鑒價(jià)值,感興趣的朋友一起看看吧2016-09-09

