国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

多線程異步調用等待響應結果后繼續處理

2019-11-11 00:14:41
字體:
來源:轉載
供稿:網友
1、在有響應的時候,使用ResponseFuture對象,并在onResponse方法中,將響應設置到Futrue中。

import com.google.common.util.concurrent.AbstractFuture;

public class ResponseFuture<JsonPRotocol>extends AbstractFuture<JsonProtocol>

{

    private final Executorexecutor;

    public ResponseFuture()

    {

        if (ThreadLocalUtil.get("isServer") ==null)

        {

            //TODO 這里是錯誤的,把這行代碼移到一個單例的全局共享中取,避免每次new。如果是服務端,那么所有的服務端都共享一個線程池

            executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(),

                    new RpcThreadFacotry("CallBack"));

        }

        else

        {

            //單線程執行器

            executor = MoreExecutors.directExecutor();

        }

    }

    /**

     * 當響應回來的時候,結果被設置到future中,因此從future中可以獲得一個異步的響應結果

     * @param responseProtocol

     */

    public void onResponse(JsonProtocolresponseProtocol)

    {

        //向future中設置值

        super.set(responseProtocol);

    }

    /**

     * 當響應有結果時候可以直接runnable的方法

     * @param runnable

     */

    public void addCallBack(Runnablerunnable)

    {

        super.addListener(runnable,executor);

    }

}

2、等待線程獲得響應結果(使用future.get阻塞等待異步線程的響應)

        ResponseFuture<JsonProtocol>reponseFuture = client.futureInvoke(JsonProtocolReqeust);

        JsonProtocol JsonProtocolResponse =null;

        try

        {

            JsonProtocolResponse =reponseFuture.get(JsonProtocolReqeust.getRpcMetadata().getTimeOut(),

                    TimeUnit.MILLISECONDS);

        }

        catch (ExecutionException e){}

        catch (TimeoutException e)

        {

            throw new RuntimeException("調用遠程服務響應超時",e);

        }


上一篇:求二叉樹的深度

下一篇:Filp Game

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 安乡县| 玉田县| 沁水县| 肃北| 东至县| 洛扎县| 当雄县| 犍为县| 资中县| 阿拉尔市| 灵丘县| 屯留县| 滦平县| 西吉县| 准格尔旗| 南京市| 澄迈县| 贡嘎县| 洛南县| 正定县| 高雄市| 兴宁市| 娄底市| 红桥区| 米易县| 扬州市| 新乐市| 峨山| 常德市| 万山特区| 司法| 北安市| 岑溪市| 柳河县| 临武县| 扶沟县| 吕梁市| 桂阳县| 宜兰市| 怀安县| 聂拉木县|