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

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

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

2019-11-11 00:52:24
字體:
來源:轉載
供稿:網友
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);

        }


上一篇:第三章 操作符

下一篇:裝船問題

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 丘北县| 犍为县| 澄城县| 天镇县| 军事| 根河市| 苗栗市| 二连浩特市| 丹东市| 延津县| 绥滨县| 东海县| 洮南市| 勃利县| 玉门市| 呈贡县| 新化县| 吉首市| 杂多县| 衡阳市| 阜新市| 怀集县| 垫江县| 沙雅县| 宝清县| 宿迁市| 遂昌县| 景德镇市| 志丹县| 嘉黎县| 汉中市| 西林县| 浮梁县| 铜山县| 达拉特旗| 平泉县| 安溪县| 柳州市| 石景山区| 确山县| 晋城|