用几个请求终止Java中的线程?

时间:2019-07-15 00:56:35

标签: java android

假设我在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中,解决此问题的方法是什么?最好在一个成功请求之后终止线程池中的所有先前请求,这怎么办?

1 个答案:

答案 0 :(得分:0)

如果您要发送每个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来确保仅一次请求,并在获取锁定以发送请求时为后续请求设置超时。

此外,如果您只希望用户以较低的频率发送请求,例如1次/ 10s。您可以声明一个变量以保留上次发送请求,并进行每次检查最后执行时间与当前时间之间的持续时间。