如何在java中强制终止有时间限制的线程?
我试图找到一种方法来设置运行代码块的时间限制(时间到了强制终止),而不修改代码块的内部结构。下面是我试图做的:我首先从这个链接复制了TimeLimitedCodeBlock类:如何在java中强制终止有时间限制的线程?,java,terminate,Java,Terminate,我试图找到一种方法来设置运行代码块的时间限制(时间到了强制终止),而不修改代码块的内部结构。下面是我试图做的:我首先从这个链接复制了TimeLimitedCodeBlock类: 而且它没有终止。我应该如何修复它以使其终止?我曾经执行过类似操作的代码片段: LOG.info("Time limited task started on monitored thread, with limit (" + limit + ")"); final ZonedDateTime start = no
而且它没有终止。我应该如何修复它以使其终止?我曾经执行过类似操作的代码片段:
LOG.info("Time limited task started on monitored thread, with limit (" + limit + ")");
final ZonedDateTime start = nowUTC();
final Thread thread = new Thread(toRun);
thread.setDaemon(true);
final List<Throwable> exceptions = new ArrayList<>();
thread.setUncaughtExceptionHandler((t, e) -> {
exceptions.add(e);
});
thread.start();
// Check and wait for completion.
while (thread.isAlive()) {
if (!isWithinLimit(start, nowUTC())) {
LOG.error("Interrupting thread, did not complete before limit (" + limit + ")");
try {
thread.interrupt();
} catch (Exception e) {
e.printStackTrace();
}
throw new TimeLimitExceedException("Execution limit of " + limit
+ " exceeded. (Has been running since " + start + ")");
}
try {
Thread.sleep(POLLING_PERIOD.toMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// If it failed because of an exception, we want to trigger this.
if (!exceptions.isEmpty()) {
final Throwable exception = exceptions.get(0);
if (exception instanceof RuntimeException) {
throw (RuntimeException) exception;
} else {
throw new RuntimeException(exception);
}
}
final Duration runTime = Duration.between(start, nowUTC());
LOG.info("Time limited task has completed in (" + runTime + ") vs limit of (" + limit
+ ").");
LOG.info(“在受监视线程上启动了有时间限制的任务,有限制(“+limit+”));
最终ZonedDateTime开始=nowUTC();
最终螺纹=新螺纹(toRun);
setDaemon(true);
最终列表异常=新的ArrayList();
线程.setUncaughtExceptionHandler((t,e)->{
例外情况。添加(e);
});
thread.start();
//检查并等待完成。
while(thread.isAlive()){
如果(!isWithinLimit(start,nowUTC())){
LOG.error(“中断线程,未在限制(“+limit+”)之前完成”);
试一试{
thread.interrupt();
}捕获(例外e){
e、 printStackTrace();
}
抛出新的TimeLimitExceedException(“执行限制”+限制
+“已超出。(自“+启动+”)以来一直在运行);
}
试一试{
sleep(POLLING_PERIOD.toMillis());
}捕捉(中断异常e){
e、 printStackTrace();
}
}
//如果由于异常而失败,我们希望触发它。
如果(!exceptions.isEmpty()){
最终可丢弃异常=异常。获取(0);
if(运行时异常的异常实例){
抛出(RuntimeException)异常;
}否则{
抛出新的RuntimeException(异常);
}
}
final Duration runTime=Duration.between(start,nowUTC());
LOG.info(“有时间限制的任务已在(“+runTime+”)中完成)与(“+limit”)的限制
+ ").");
TLDR:
我只需启动我正在运行的任何一个新线程,该线程被设置为守护进程(以防万一它是最后一个运行的线程),然后获取对该线程的引用并轮询它,如果超过时间限制,则调用thread.interrupt()
其他语境&钟声和口哨
- 这是具有其他状态的类的一部分,例如持续时间和它正在运行的内容
- 还可以跟踪一些异常,以便在必要时在末尾将其吐出
Thread.stop()
强制终止,这是不推荐使用的,不应使用。您是否熟悉CompletableFuture
?TimeLimitedCodeBlock不会终止线程或执行。它只允许您在超时后停止等待结果。在主方法的和处放置一个系统,然后查看何时打印该系统。
public static void main(String [] args)
{
try{
TimeLimitedCodeBlock.runWithTimeout(new Runnable()
{
public void run()
{
try{
while(true){}
}catch(Exception e){}
}},1,TimeUnit.SECONDS);
}
catch(Exception e){}
}
LOG.info("Time limited task started on monitored thread, with limit (" + limit + ")");
final ZonedDateTime start = nowUTC();
final Thread thread = new Thread(toRun);
thread.setDaemon(true);
final List<Throwable> exceptions = new ArrayList<>();
thread.setUncaughtExceptionHandler((t, e) -> {
exceptions.add(e);
});
thread.start();
// Check and wait for completion.
while (thread.isAlive()) {
if (!isWithinLimit(start, nowUTC())) {
LOG.error("Interrupting thread, did not complete before limit (" + limit + ")");
try {
thread.interrupt();
} catch (Exception e) {
e.printStackTrace();
}
throw new TimeLimitExceedException("Execution limit of " + limit
+ " exceeded. (Has been running since " + start + ")");
}
try {
Thread.sleep(POLLING_PERIOD.toMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// If it failed because of an exception, we want to trigger this.
if (!exceptions.isEmpty()) {
final Throwable exception = exceptions.get(0);
if (exception instanceof RuntimeException) {
throw (RuntimeException) exception;
} else {
throw new RuntimeException(exception);
}
}
final Duration runTime = Duration.between(start, nowUTC());
LOG.info("Time limited task has completed in (" + runTime + ") vs limit of (" + limit
+ ").");