Ask the question of getting multiple interface data from one interface at the same time.

I now have an interface that needs to access two interfaces at the same time to get data from the server, which is better to use Synchronize or asynchronous. I used two methods, both of which are Synchronize. The first is to create a child thread with two interfaces in it for network access, and the second is to create a thread pool to access. Is it better to access Synchronize or asynchronously? Is there a better method?
Code for the first method:

 new Thread(new Runnable() {
            @Override
            public void run() {
                String url = ConstantsUtils.HEAD_URL + "/video";
                try {
                    Response response = NetWorkRequestUtils.postRequest(url, new HomeDataObject());//
                    if (response.isSuccessful()) {
                        String json = response.body().string();
                        Log.d(TAG, "json=" + json);
                        PreferenceUtils.putString(getActivity(), url, json);//JSON
                        setInitData(json);//json
                    } else {
                        Log.d(TAG, "222222");
                        Message obtain = Message.obtain();
                        obtain.what = SHOW_INIT_DATA_FAIL;
                        mHandler.sendMessage(obtain);
                    }
                } catch (Exception e) {
                    Log.d(TAG, "33333333" + "e.printStackTrace()");
                    Message obtain = Message.obtain();
                    obtain.what = SHOW_INIT_DATA_FAIL;
                    mHandler.sendMessage(obtain);
                    e.printStackTrace();
                }

                //:,channelid
                try {
                    Response response = NetWorkRequestUtils.postRequest(ConstantsUtils.HEAD_URL + "/video/recoList", new RelatedRecommendedObject());//
                    if (response.isSuccessful()) {
                        String json = response.body().string();
                        Log.d(TAG, "=" + json);
                        setRelatedRecommendedData(json);//
                    } else {
                        Log.d(TAG, "11111111111111");
                        Message obtain = Message.obtain();
                        obtain.what = SHOW_LOAD_MORE_FAIL;
                        mHandler.sendMessage(obtain);
                    }
                } catch (Exception e) {
                    Log.d(TAG, "22222222222");
                    Message obtain = Message.obtain();
                    obtain.what = SHOW_LOAD_MORE_FAIL;
                    mHandler.sendMessage(obtain);
                    e.printStackTrace();
                }
            }
        }).start();

the second method:

 private void getHomeInitData() {
        ThreadManager.getNormalPool().execute(new InitListTask());//
        ThreadManager.getNormalPool().execute(new RelatedRecommendedTask());//
    }

    /**     */
    private class InitListTask implements Runnable {
        @Override
        public void run() {
            String url = ConstantsUtils.HEAD_URL + "/video";
            try {
                Response response = NetWorkRequestUtils.postRequest(url, new HomeDataObject());
                if (response.isSuccessful()) {
                    String json = response.body().string();
                    Log.d(TAG, "json=" + json);
                    PreferenceUtils.putString(getActivity(), url, json);//JSON
                    setInitData(json);//json
                } else {
                    Log.d(TAG, "222222");
                    Message obtain = Message.obtain();
                    obtain.what = SHOW_INIT_DATA_FAIL;
                    mHandler.sendMessage(obtain);
                }
            } catch (Exception e) {
                Log.d(TAG, "33333333" + "e.printStackTrace()");
                Message obtain = Message.obtain();
                obtain.what = SHOW_INIT_DATA_FAIL;
                mHandler.sendMessage(obtain);
                e.printStackTrace();
            }
        }
    }

    private class RelatedRecommendedTask implements Runnable{
        @Override
        public void run() {
            try {
                Response response = NetWorkRequestUtils.postRequest(ConstantsUtils.HEAD_URL + "/video/recoList", new RelatedRecommendedObject());
                if (response.isSuccessful()) {
                    String json = response.body().string();
                    Log.d(TAG, "=" + json);
                    setRelatedRecommendedData(json);//
                } else {
                    Log.d(TAG, "11111111111111");
                    Message obtain = Message.obtain();
                    obtain.what = SHOW_LOAD_MORE_FAIL;
                    mHandler.sendMessage(obtain);
                }
            } catch (Exception e) {
                Log.d(TAG, "22222222222");
                Message obtain = Message.obtain();
                obtain.what = SHOW_LOAD_MORE_FAIL;
                mHandler.sendMessage(obtain);
                e.printStackTrace();
            }
        }
    }
The

ThreadManager class says:

public class ThreadManager {

    private static ThreadPoolProxy mNormalPool   = new ThreadPoolProxy(3, 3, 5 * 1000);
    private static ThreadPoolProxy mDownloadPool = new ThreadPoolProxy(3, 3, 5 * 1000);
    public static ThreadPoolProxy getNormalPool() {
        return mNormalPool;
    }
    public static ThreadPoolProxy getDownloadPool() {
        return mDownloadPool;
    }

    public static class ThreadPoolProxy {
        private final int                mCorePoolSize;
        private final int                mMaximumPoolSize;
        private final long               mKeepAliveTime;
        private       ThreadPoolExecutor mPool;
        public ThreadPoolProxy(int corePoolSize, int maximumPoolSize, long keepAliveTime) {
            this.mCorePoolSize = corePoolSize;
            this.mMaximumPoolSize = maximumPoolSize;
            this.mKeepAliveTime = keepAliveTime;
        }
        private void initPool() {
            if (mPool == null || mPool.isShutdown()) {
                //                int corePoolSize = 1;//
                //                int maximumPoolSize = 3;//
                //                long keepAliveTime = 5 * 1000;//
                TimeUnit                unit      = TimeUnit.MILLISECONDS;//
                BlockingQueue<Runnable> workQueue = null;//

                //                workQueue = new ArrayBlockingQueue<Runnable>(3);//FIFO,
                workQueue = new LinkedBlockingQueue();//
                //                workQueue = new PriorityBlockingQueue();

                ThreadFactory threadFactory = Executors.defaultThreadFactory();//

                RejectedExecutionHandler handler = null;//

                //                handler = new ThreadPoolExecutor.DiscardOldestPolicy();//
                //                handler = new ThreadPoolExecutor.AbortPolicy();//
                handler = new ThreadPoolExecutor.DiscardPolicy();//
                //                handler = new ThreadPoolExecutor.CallerRunsPolicy();//,
                //                new Thread(task).start();

                mPool = new ThreadPoolExecutor(mCorePoolSize,
                                               mMaximumPoolSize,
                                               mKeepAliveTime,
                                               unit,
                                               workQueue,
                                               threadFactory,
                                               handler);
            }
        }

        /**
         * 
         * @param task
         */
        public void execute(Runnable task) {
            initPool();
            //
            mPool.execute(task);
        }
        public Future<?> submit(Runnable task) {
            initPool();
            return mPool.submit(task);
        }
        public void remove(Runnable task) {
            if (mPool != null && !mPool.isShutdown()) {
                mPool.getQueue()
                     .remove(task);
            }
        }
    }
}
Mar.02,2021

Rx, what about it?

as you can see from the code: the recommended data pull is pulled after the principal data. If the recommended data is already displayed before the principal data is displayed, then this interaction is very strange, unless the principal data is empty. Therefore, it is not appropriate to use simple asynchronous requests. At this point, Rx can perform its magic as follows:

RxJava + RxAndroid + Retrofit + RxLifecycle can solve this kind of need very well.

p.s. All of the above can be found at github

.

this is not just a matter of two interfaces on a page, if there are 30 + interfaces in the project, or more, are you tired to write this, do you have a headache to maintain? It is recommended to encapsulate the request initiated by NetWorkRequestUtils, and pass a callback acceptance result, and the thread pool is used internally in NetWorkRequestUtils.
as to whether the two interfaces you mentioned are two-thread processing or one-thread serial, it depends on whether the two interfaces in your business are sequentially dependent. If not, it is recommended to deal with them separately.

Menu