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

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

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

2019-11-10 23:54:53
字體:
來源:轉載
供稿:網友
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);

        }


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 龙岩市| 无锡市| 白银市| 瑞安市| 根河市| 堆龙德庆县| 伊金霍洛旗| 巴东县| 夏河县| 涡阳县| 客服| 洪湖市| 定州市| 微博| 九江县| 嘉义市| 尼勒克县| 汨罗市| 老河口市| 革吉县| 钦州市| 林甸县| 天祝| 桐柏县| 长阳| 安远县| 汉源县| 五原县| 方正县| 平罗县| 如皋市| 邵阳市| 定安县| 西城区| 洛扎县| 益阳市| 宣武区| 镇江市| 上林县| 盐山县| 南城县|