简体   繁体   English

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

[英]Terminating threads in Java with several requests?

Suppose I have a method in a CLIENT Java application (ie Android app) 假设我在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

In anger, the user taps the button 100 times, then 100 requests have been submitted into the ThreadPool. 生气时,用户轻击按钮100次,然后已将100个请求提交到ThreadPool中。 2 bad things occur: 发生2件事:

(1) Costly request computed 100 times (1)昂贵的请求计算了100次

(2) The UI is refreshed 100 times after each return. (2)每次返回后,UI都会刷新100次。

These are all very big issues. 这些都是非常大的问题。 In Java, what's the way of solving this? 在Java中,解决此问题的方法是什么? It would be best to terminate all preceeding requests in the thread pool after one sucessful request, how can this be done? 最好是在一个成功请求之后终止线程池中的所有先前请求,这怎么办?

If you want send each http request, but no concurrency。 Lock may help you here. 如果您想发送每个http请求,但没有并发Lock可以在这里为您提供帮助。 Below pseudo-code: 下面的伪代码:

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

We use a Lock to ensure only one request at same time, and set a timeout to follow-up request when get lock to send a request. 我们使用Lock来确保同时只有一个请求,并在获取Lock来发送请求时将超时设置为后续请求。

In addition , if you just want a user just send request in a low frequency,like 1 time/10s。You can declare a variable to keep last time the request sent, and every time check the duration between the last execute time and current time. 另外 ,如果只希望用户以较低的频率发送请求,例如1次/ 10s。可以声明一个变量来保留上次发送请求的时间,并每次检查上次执行时间与当前时间之间的持续时间。 。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM