我現(xiàn)在有一個(gè)界面需要同時(shí)訪問(wèn)兩個(gè)接口從服務(wù)器獲取數(shù)據(jù),是用同步還是異步的方式好.我用了兩種方法,都是同步的.第一種是創(chuàng)建一個(gè)子線程,同時(shí)把兩個(gè)接口放在里面做網(wǎng)絡(luò)訪問(wèn);第二種是創(chuàng)建線程池去訪問(wèn).請(qǐng)問(wèn)同步方式還是異步方式訪問(wèn)好?有更優(yōu)的方法嗎?
第一種方法的代碼:
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數(shù)據(jù)
setInitData(json);//獲取到j(luò)son數(shù)據(jù)后回調(diào)
} else {
Log.d(TAG, "布局一請(qǐng)求失敗222222");
Message obtain = Message.obtain();
obtain.what = SHOW_INIT_DATA_FAIL;
mHandler.sendMessage(obtain);
}
} catch (Exception e) {
Log.d(TAG, "布局一請(qǐng)求失敗33333333" + "e.printStackTrace()");
Message obtain = Message.obtain();
obtain.what = SHOW_INIT_DATA_FAIL;
mHandler.sendMessage(obtain);
e.printStackTrace();
}
//二:獲取多布局相關(guān)推薦數(shù)據(jù),當(dāng)前首頁(yè)模塊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);//設(shè)置相關(guān)推薦數(shù)據(jù)
} 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();
第二種方法:
private void getHomeInitData() {
ThreadManager.getNormalPool().execute(new InitListTask());//獲取布局一初始列表的數(shù)據(jù)
ThreadManager.getNormalPool().execute(new RelatedRecommendedTask());//獲取布局二相關(guān)推薦的數(shù)據(jù)
}
/** 獲取布局一初始列表的數(shù)據(jù) */
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數(shù)據(jù)
setInitData(json);//獲取到j(luò)son數(shù)據(jù)后回調(diào)
} else {
Log.d(TAG, "布局一請(qǐng)求失敗222222");
Message obtain = Message.obtain();
obtain.what = SHOW_INIT_DATA_FAIL;
mHandler.sendMessage(obtain);
}
} catch (Exception e) {
Log.d(TAG, "布局一請(qǐng)求失敗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);//設(shè)置相關(guān)推薦數(shù)據(jù)
} 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();
}
}
}
ThreadManager類(lèi)是這樣寫(xiě)的:
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;//保持存活的時(shí)間
TimeUnit unit = TimeUnit.MILLISECONDS;//單位
BlockingQueue<Runnable> workQueue = null;//阻塞隊(duì)列
// workQueue = new ArrayBlockingQueue<Runnable>(3);//FIFO,大小有限制
workQueue = new LinkedBlockingQueue();//
// workQueue = new PriorityBlockingQueue();
ThreadFactory threadFactory = Executors.defaultThreadFactory();//線程工廠
RejectedExecutionHandler handler = null;//異常捕獲器
// handler = new ThreadPoolExecutor.DiscardOldestPolicy();//去掉隊(duì)列中首個(gè)任務(wù),將新加入的放到隊(duì)列中去
// handler = new ThreadPoolExecutor.AbortPolicy();//觸發(fā)異常
handler = new ThreadPoolExecutor.DiscardPolicy();//不做任何處理
// handler = new ThreadPoolExecutor.CallerRunsPolicy();//直接執(zhí)行,不歸線程池控制,在調(diào)用線程中執(zhí)行
// new Thread(task).start();
mPool = new ThreadPoolExecutor(mCorePoolSize,
mMaximumPoolSize,
mKeepAliveTime,
unit,
workQueue,
threadFactory,
handler);
}
}
/**
* 執(zhí)行任務(wù)
* @param task
*/
public void execute(Runnable task) {
initPool();
//執(zhí)行任務(wù)
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);
}
}
}
}
這個(gè)不僅僅是一個(gè)頁(yè)面2個(gè)接口的問(wèn)題,如果項(xiàng)目里有30+接口,或者更多,你這么寫(xiě)累不累,維護(hù)起來(lái)頭疼不?建議封裝到NetWorkRequestUtils,發(fā)起請(qǐng)求傳遞一個(gè)callback接受結(jié)果,NetWorkRequestUtils內(nèi)部用線程池。
至于你說(shuō)的兩個(gè)接口是兩個(gè)線程處理,還是一個(gè)線程串行,這個(gè)看你業(yè)務(wù)上兩個(gè)接口有沒(méi)有順序依賴,如果沒(méi)有,建議分開(kāi)處理。
北大青鳥(niǎo)APTECH成立于1999年。依托北京大學(xué)優(yōu)質(zhì)雄厚的教育資源和背景,秉承“教育改變生活”的發(fā)展理念,致力于培養(yǎng)中國(guó)IT技能型緊缺人才,是大數(shù)據(jù)專(zhuān)業(yè)的國(guó)家
北大青鳥(niǎo)中博軟件學(xué)院創(chuàng)立于2003年,作為華東區(qū)著名互聯(lián)網(wǎng)學(xué)院和江蘇省首批服務(wù)外包人才培訓(xùn)基地,中博成功培育了近30000名軟件工程師走向高薪崗位,合作企業(yè)超4
中公教育集團(tuán)創(chuàng)建于1999年,經(jīng)過(guò)二十年潛心發(fā)展,已由一家北大畢業(yè)生自主創(chuàng)業(yè)的信息技術(shù)與教育服務(wù)機(jī)構(gòu),發(fā)展為教育服務(wù)業(yè)的綜合性企業(yè)集團(tuán),成為集合面授教學(xué)培訓(xùn)、網(wǎng)
達(dá)內(nèi)教育集團(tuán)成立于2002年,是一家由留學(xué)海歸創(chuàng)辦的高端職業(yè)教育培訓(xùn)機(jī)構(gòu),是中國(guó)一站式人才培養(yǎng)平臺(tái)、一站式人才輸送平臺(tái)。2014年4月3日在美國(guó)成功上市,融資1
曾工作于聯(lián)想擔(dān)任系統(tǒng)開(kāi)發(fā)工程師,曾在博彥科技股份有限公司擔(dān)任項(xiàng)目經(jīng)理從事移動(dòng)互聯(lián)網(wǎng)管理及研發(fā)工作,曾創(chuàng)辦藍(lán)懿科技有限責(zé)任公司從事總經(jīng)理職務(wù)負(fù)責(zé)iOS教學(xué)及管理工作。
浪潮集團(tuán)項(xiàng)目經(jīng)理。精通Java與.NET 技術(shù), 熟練的跨平臺(tái)面向?qū)ο箝_(kāi)發(fā)經(jīng)驗(yàn),技術(shù)功底深厚。 授課風(fēng)格 授課風(fēng)格清新自然、條理清晰、主次分明、重點(diǎn)難點(diǎn)突出、引人入勝。
精通HTML5和CSS3;Javascript及主流js庫(kù),具有快速界面開(kāi)發(fā)的能力,對(duì)瀏覽器兼容性、前端性能優(yōu)化等有深入理解。精通網(wǎng)頁(yè)制作和網(wǎng)頁(yè)游戲開(kāi)發(fā)。
具有10 年的Java 企業(yè)應(yīng)用開(kāi)發(fā)經(jīng)驗(yàn)。曾經(jīng)歷任德國(guó)Software AG 技術(shù)顧問(wèn),美國(guó)Dachieve 系統(tǒng)架構(gòu)師,美國(guó)AngelEngineers Inc. 系統(tǒng)架構(gòu)師。