我想在固定的时间内运行一个线程.如果不能在这段时间内完成,我想要么杀死它,抛出一些异常,要么以某种方式处理它.怎么做呢?

就像我从this thread岁起算出的那样,有一种方法可以做到这一点 是在Thread的run()方法中使用TimerTask.

有更好的解决方案吗?

 
EDIT: Adding a bounty as I needed a clearer answer. The ExecutorService code given below does not address my problem. Why should I sleep() after executing (some code - I have no handle over this piece of code)? If the code is completed and the sleep() is interrupted, how can that be a timeOut?

需要执行的任务不在我的控制范围之内.它可以是任何一段代码.问题是这段代码可能会进入无限循环.我不希望这种事发生.所以,我只想在单独的线程中运行该任务.父线程必须等到该线程完成,并且需要知道任务的状态(即它是否超时、是否发生异常或是否成功).如果任务进入无限循环,我的父线程将无限期地等待,这不是理想的情况.

推荐答案

实际上,用ExecutorService而不是Timer,这里有一个SSCCE:

package com.stackoverflow.q2275443;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class Test {
    public static void main(String[] args) throws Exception {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<String> future = executor.submit(new Task());

        try {
            System.out.println("Started..");
            System.out.println(future.get(3, TimeUnit.SECONDS));
            System.out.println("Finished!");
        } catch (TimeoutException e) {
            future.cancel(true);
            System.out.println("Terminated!");
        }

        executor.shutdownNow();
    }
}

class Task implements Callable<String> {
    @Override
    public String call() throws Exception {
        Thread.sleep(4000); // Just to demo a long running task of 4 seconds.
        return "Ready!";
    }
}

Future#get()方法中稍微使用timeout参数,例如将其增加到5,您将看到线程结束.你可以在catch (TimeoutException e)挡路中截取超时.

Update:为了澄清概念上的误解,sleep()not.它仅用于SSCCE/演示目的.只需要做your个长时间运行的任务,而不是sleep()个.在长时间运行的任务中,您应该判 break line 程是否不是interrupted,如下所示:

while (!Thread.interrupted()) {
    // Do your long running task here.
}

Java相关问答推荐

如何使用Spring Data从MongoDB文档中包含的数组中 Select 单个元素?

验证使用GCP生成的非对称密钥时签名不起作用

使用json参数通过单击jSP文件中的按钮来运行server时出现问题

当列顺序更改时,Table View列列表的Change. wasPermanted()总是返回假

是否需要关闭Executors返回的执行器.newVirtualThreadPerTaskExecutor()?

如果一个子类没有构造函数,超类也没有构造函数,那么为什么我可以构造子类的实例呢?

Intellij显示项目语言级别最高为12,尽管有java版本17 SDK

JUnit—如何模拟局部变量对象方法调用

Java FX中的河内之塔游戏-在游戏完全解决之前什么都不会显示

扩展到弹出窗口宽度的JavaFX文本字段

在向WebSphere中的文档添加元素时iText挂起

如何在JavaFX循环中完美地制作一个AudioClip/MediaPlayer?

Dijkstra搜索算法的实现

JOLT根据值删除并保留其余的json键

从12小时开始的日期模式

Java System.getProperty在哪里检索user.home?

Java中的一个错误';s stdlib SocksSocketImpl?

PhantomReference无法访问时会发生什么?

java21预览未命名的符号用于try-with-resources

转换为JSON字符串时,日期按天递减-Java