第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請及時(shí)綁定郵箱和手機(jī)立即綁定

想問下方法內(nèi)部定義鎖和方法塊不生效的原因是?

-------------------synchronized不生效---------------
public?class?tx?implements?Runnable{
static?Integer??a=new?Integer(0);
????static??int??i=0;
public?void?increase(){
????Integer?integer?=?new?Integer(0);
????synchronized(integer){
????i++;}
}
@Override
public?void?run(){
????for?(int?j?=0?;?j<10000;j++){
????????increase();
????}
}

public?static?void?main(String[]?args)?throws?InterruptedException?{
????tx?tx?=?new?tx();
????Thread?t1?=?new?Thread(tx);
????Thread?t2?=?new?Thread(tx);
????t1.start();
????t2.start();
????t1.join();
????t2.join();
????System.out.println(i);
}
----------------分割線(synchronized生效)---------------------
public?class?tx?implements?Runnable{
static?Integer??a=new?Integer(0);
????static??int??i=0;
?????Integer?integer?=?new?Integer(0);---》放入increase方法內(nèi)定義不生效
public?void?increase(){?
????synchronized(integer){
????i++;}
}
@Override
public?void?run(){
????for?(int?j?=0?;?j<10000;j++){
????????increase();
????}
}

public?static?void?main(String[]?args)?throws?InterruptedException?{
????tx?tx?=?new?tx();
????Thread?t1?=?new?Thread(tx);
????Thread?t2?=?new?Thread(tx);
????t1.start();
????t2.start();
????t1.join();
????t2.join();
????System.out.println(i);
}


正在回答

2 回答

兩個(gè)線程使用的是兩個(gè)不同的鎖,線程之間沒有相互影響。

0 回復(fù) 有任何疑惑可以回復(fù)我~
public?void?increase(){
????Integer?integer?=?new?Integer(0);
????synchronized(integer){
????i++;}
}
@Override
public?void?run(){
????for?(int?j?=0?;?j<10000;j++){
????????increase();
????}
}

這樣寫每次執(zhí)行run方法鎖都不一樣。

0 回復(fù) 有任何疑惑可以回復(fù)我~

舉報(bào)

0/150
提交
取消
Java高并發(fā)之魂:synchronized深度解析
  • 參與學(xué)習(xí)       36668    人
  • 解答問題       27    個(gè)

從0開始徹底學(xué)會(huì)高并發(fā)場景下不得不會(huì)的synchronized

進(jìn)入課程

想問下方法內(nèi)部定義鎖和方法塊不生效的原因是?

我要回答 關(guān)注問題
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)