[英]Terminating threads in Java with several requests?
假設我在CLIENT Java應用程序(即Android應用程序)中有一個方法
ExecutorService pool = ExecutorsService.newFixedThreadPool(1); //1 thread in pool
public void makeHTTPRequestVeryVeryCostly() {
/* IN A BACKGROUND THREAD */
CompleteableFuture<String> s = CompleteableFuture.supplyAsync(() -> makeCostlyReq, pool));
s.get();
updateTheUserUIInTheMainUIThread(s); //Update with s
}
button.onClicklistener((b) -> makeHTTPRequestVeryVeryCostly()); // some button in the UI that will make the http request
生氣時,用戶輕擊按鈕100次,然后已將100個請求提交到ThreadPool中。 發生2件事:
(1)昂貴的請求計算了100次
(2)每次返回后,UI都會刷新100次。
這些都是非常大的問題。 在Java中,解決此問題的方法是什么? 最好是在一個成功請求之后終止線程池中的所有先前請求,這怎么辦?
如果您想發送每個http請求,但沒有並發Lock
可以在這里為您提供幫助。 下面的偽代碼:
ExecutorService pool = ExecutorsService.newFixedThreadPool(1); //1 thread in pool
Lock httpRequestLock = new ReentrantLock();
public void makeHTTPRequestVeryVeryCostly() {
boolean locked = httpRequestLock.tryLock(10, TimeUnit.SECONDS);
if(!locked){
//can't get the request lock util timeout(10s)
return;
}
try{
/* IN A BACKGROUND THREAD */
CompleteableFuture<String> s = CompleteableFuture.supplyAsync(() -> makeCostlyReq, pool));
s.get();
updateTheUserUIInTheMainUIThread(s); //Update with s
}finally{
httpRequestLock.unlock();
}
}
button.onClicklistener((b) -> makeHTTPRequestVeryVeryCostly()); // some button in the UI that will make the http request
我們使用Lock
來確保同時只有一個請求,並在獲取Lock來發送請求時將超時設置為后續請求。
另外 ,如果只希望用戶以較低的頻率發送請求,例如1次/ 10s。可以聲明一個變量來保留上次發送請求的時間,並每次檢查上次執行時間與當前時間之間的持續時間。 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.