java - 具有提到 timeOut 的未来对象为下一个线程不断增加(timeOut 未申请 Java 中 ThreadPool 中的所有线程)
问题描述
工作线程在此处定义,运行方法中的繁重任务为 10 秒
import java.util.Date;
import java.util.Random;
import java.util.concurrent.Callable;
public class WorkerThread implements Callable {
private String command;
private long startTime;
public WorkerThread(String s){
this.command=s;
}
@Override
public Object call() throws Exception {
startTime = System.currentTimeMillis();
System.out.println(new Date()+"::::"+Thread.currentThread().getName()+" Start. Command = "+command);
Random generator = new Random();
Integer randomNumber = generator.nextInt(5);
processCommand();
System.out.println(new Date()+ ":::"+Thread.currentThread().getName()+" End.::"+command+"::"+ (System.currentTimeMillis()-startTime));
return randomNumber+"::"+this.command;
}
private void processCommand() {
try {
Thread.sleep(10000);
}
catch (Exception e) {
System.out.println("Interrupted::;Process Command:::"+this.command);
}
}
@Override
public String toString(){
return this.command;
}
}
将我的 WorkerPool 定义为 Future get Timeout 为 1 秒。
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class WorkerPool {
static BlockingQueue queue=new LinkedBlockingQueue(2);
static RejectedExecutionHandlerImpl rejectionHandler = new RejectedExecutionHandlerImpl();
static ThreadFactory threadFactory = Executors.defaultThreadFactory();
static ThreadPoolExecutor executorPool = new ThreadPoolExecutor(4, 4, 11, TimeUnit.SECONDS, queue, threadFactory, rejectionHandler);
static MyMonitorThread monitor = new MyMonitorThread(executorPool, 3);
public static void main(String args[]) throws InterruptedException, TimeoutException{
List<Future<Integer>> list = new ArrayList<Future<Integer>>();
for(int i=1; i< 5; i++){
WorkerThread worker = new WorkerThread("WorkerThread:::_"+i);
Future<Integer> future = executorPool.submit(worker);
list.add(future);
}
for(Future<Integer> future : list){
try {
try {
future.get(1000, TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
future.cancel(true);
}
} catch (Exception e) {
e.printStackTrace();
}
}
executorPool.shutdown();
}
}
线程的超时对于未来的线程不断增加,我的期望应该是,如果所有线程都花费超过 1 秒,那么应该在 ! 第二。
在 aboce 场景中,工作线程需要 10 秒来处理,但我在 1 秒内超时了我的所有 4 个线程,但每个线程时间每个任务增加 1 秒。
第一个 thred timeOut 是 1 第二个 second thred timeOut 是 2 Second 第三个 thred timeOut 是 3 秒。
为什么所有线程都不会在 1 秒内中断?我的代码有问题吗?
解决方案
Because you are waiting sequentially in a loop in this section:
for(Future<Integer> future : list) {
...
future.get(1000, TimeUnit.MILLISECONDS);
...
}
Basically the flow is:
- all workers 1 .. 4 start
- you wait for worker A to finish
- 1 second passes, TimeoutException (worker A was alive for 1 second)
- you wait for worker B to finish
- 1 second passes, TimeoutException (worker B was alive for 2 seconds)
- you wait for worker C to finish
- 1 second passes, TimeoutException (worker C was alive for 3 seconds)
- ... same for D ...
If you want to wait for at most 1 second for all workers you need to count how much time you spent waiting so far, and then wait for remaining time. Something like the pseudocode:
long quota = 1000
for (Future future : futures) {
long start = System.currentTimeMillis
try {
future.get(quota, MILLISECONDS)
}
catch (TimeoutException e) {
future.cancel(true)
}
finally {
long spent = System.currentTimeMillis() - start
quota -= spent
if (quota < 0) {quota = 0} // the whole block is going to execute longer than .get() only
}
}
推荐阅读
- javascript - 如何获取有关 .innerText 的所有样式信息
- php - 在 WooCommerce 电子邮件通知的文本中显示送货地址2
- cassandra - 在 Cassandra 上创建键空间后,节点进入耗尽状态
- c# - 如何在剃刀视图中添加两个变量
- android - 如何跨平台与Android和IOS
- android - Firebase 数据更新滞后 - 多人游戏
- android - Firebase 未记录安装引荐来源网址
- visual-studio - Docker AspNet Core + Couchbase
- docker - 无法从 docker 映像连接到 dockerhost
- javascript - 循环遍历 Microdata 以提取 itemprop 和 text 值