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

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

在類構(gòu)造函數(shù)中調(diào)用線程的替代方法

在類構(gòu)造函數(shù)中調(diào)用線程的替代方法

慕工程0101907 2021-05-12 17:22:21
我有一個(gè)可以被多個(gè)線程訪問的類。我希望該類在響應(yīng)調(diào)用(getSomething)之前先做一些事情。我當(dāng)時(shí)想開始在類構(gòu)造函數(shù)中啟動(dòng)SampleThreadinside,但我不喜歡在構(gòu)造函數(shù)中啟動(dòng)線程的想法。我正在考慮做這樣的事情,但是我不確定這是否正確。將在類上調(diào)用getSomething的第一個(gè)線程將啟動(dòng)一個(gè)線程。但是我仍然不確定這是否正確。。我擔(dān)心多個(gè)SampleThread會(huì)運(yùn)行,而我只希望它運(yùn)行一次。public class A{    private final AtomicBoolean isReady = new AtomicBoolean(false);    public A{    }    public void getSomething(){        if(!isReady.get()){            new SampleThread().start();        }        //continue with the rest of the method    }}public class SampleThread{    public void run(){        //Do some long running task once done        isReady.set(true);    }}我沒有辦法添加一個(gè)名為start()的方法,在該方法中我可以調(diào)用我的SampleThread,因?yàn)樵摲椒ㄊ怯煽蚣苷{(diào)用的。有什么提示嗎?
查看完整描述

1 回答

?
小唯快跑啊

TA貢獻(xiàn)1863條經(jīng)驗(yàn) 獲得超2個(gè)贊

這種方式具有競(jìng)爭(zhēng)條件:


public void getSomething(){

    if(!isReady.get()){

        new SampleThread().start();

    }

    //continue with the rest of the method

}

這是原子的: if(!isReady.get())但是與之關(guān)聯(lián)的條件語(yǔ)句的主體不是:


{

    new SampleThread().start();

}

因此,您可以啟動(dòng)兩次該線程。


同步邏輯可防止出現(xiàn)競(jìng)爭(zhēng)情況。這也將增加對(duì)象上潛在的鎖定數(shù)量,但是if(!isReady.get())應(yīng)該快速執(zhí)行,這應(yīng)該是可以接受的。

請(qǐng)注意,AtomicBoolean如果布爾值僅在同步語(yǔ)句中使用,則可能不需要使用。


所以這里有兩種方式可以根據(jù)您的要求。


1)為了getSomething()開始第一次調(diào)用,SampleThread 并且其他線程在執(zhí)行之前等待初始化結(jié)束getSomething():


public void getSomething(){

    synchronized(this){

      // init the logic 

      if(!isReady){

          SampleThread t = new SampleThread();

          t.start(); 

          t.join();  // wait for the SampleThread thread termination

          isReady.set(true);           

      }         

      // execute the next only as the init thread was terminated

      if(isReady){

         //continue with the rest of the method

      }


    }     

}

2)為了讓在第一次調(diào)用getSomething()開始SampleThread和別人線程不會(huì)等待此初始化執(zhí)行前結(jié)束getSomething():


public void getSomething(){

    synchronized(this){

      // init the logic once

      if(!isReady.get()){

          SampleThread t = new SampleThread();

          t.start();                                   

      }                                   

    }

    //continue with the rest of the method       

}

并設(shè)置isReady以true在年底run()的SampleThread:


public void run(){

    //Do some long running task once done

    isReady.set(true);

}


查看完整回答
反對(duì) 回復(fù) 2021-05-26
  • 1 回答
  • 0 關(guān)注
  • 163 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號(hào)

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