synchronized與volatile關鍵字

2021-08-01 22:11:05 字數 2159 閱讀 9123

volatile保證其他執行緒對這個變數操作時是立即可見的,即操作的是從記憶體中讀取的最新值

無法保證原子性

只能修飾變數

public

class test

public

static

void

main(string args) throws exception

};}.start();}}

}

控制台輸出:

使用場景(dcl雙重檢測鎖):

class singleton

public

static singleton getinstance()

}return instance;}}

保證原子性

即可修飾變數也可修飾方法

會阻塞執行緒

public

class test catch (interruptedexception e)

system.out.println("increase1---->" + i);}}

public synchronized void

increase2() catch (interruptedexception e)

system.out.println("increase2---->" + i);}}

public

static

void

main(string args) throws exception ;

}.start();

new thread() ;

}.start();}}

控制台輸出:

結論:

如果乙個物件有多個synchronized方法,多個執行緒同時呼叫該物件的方法,將會同步執行,即同時只能有乙個synchronized方法被呼叫,其他呼叫將被阻塞直至該方法執行完

懶。。 直接給結論了

synchronized靜態方法和非靜態方法的區別在於給方法上鎖的物件不一樣,非靜態方法是給呼叫的物件上鎖,靜態方法是給類的class物件上鎖

public

class test catch (interruptedexception e)

system.out.println("increase1---->" + i);}}

system.out.println("increase1----------> end");

}public

void

increase2() catch (interruptedexception e)

system.out.println("increase2---->" + i);}}

system.out.println("increase2----------> end");

}public

static

void

main(string args) throws exception ;

}.start();

new thread() ;

}.start();}}

控制台輸出:

結論

synchronized方法是控制同時只能有乙個執行緒執行synchronized方法;synchronized塊是控制同時只能有乙個執行緒執行synchronized塊中的內容

Java po與vo的區別

vo,值物件 value object po,持久物件 persisent object 它們是由一組屬性和屬性的get和set方法組成。從結構上看,它們並沒有什麼不同的地方。但從其意義和本質上來看是完全不同的。vo是用new關鍵字建立,由gc 的。po則是向資料庫中新增新資料時建立,刪除資料庫中資...

領域設計 Entity與VO

要理解entity和vo,需要先理解兩個概念 狀態 和 標識 我們先來聊聊 狀態 大家肯定都在 買過東西吧!在 購買商品後,會有乙個訂單,記錄了你購買的商品資訊 店鋪資訊 還有乙個特別重要的資訊,就是訂單狀態。通過這個訂單狀態,我們可以知道我們的購物流程現在進行到哪一步了。如果你猶豫了很久才下定決心...

反射與單級VO操作

class employee public void setname string name public string get public void set string public string tostring 如果我們把要傳的屬性設定成stringlei 型別一次傳進去就會方面很多。首先...