国产探花免费观看_亚洲丰满少妇自慰呻吟_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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 宁河县| 岳池县| 平塘县| 汽车| 历史| 亚东县| 黔南| 鹰潭市| 盐边县| 连州市| 卓资县| 榆林市| 湾仔区| 旬邑县| 信宜市| 讷河市| 海晏县| 金川县| 长岛县| 扎赉特旗| 平阴县| 望都县| 道真| 锡林郭勒盟| 连云港市| 泽普县| 四会市| 库车县| 深水埗区| 海原县| 虎林市| 宽甸| 四会市| 兴城市| 察哈| 新巴尔虎右旗| 开鲁县| 利辛县| 腾冲县| 赣州市| 沁阳市|