【问题标题】:How to timeout at Java thread after the creating thread has already returned?创建线程已经返回后如何在 Java 线程处超时?
【发布时间】:2019-06-17 09:07:53
【问题描述】:

我正在尝试编写一个方法来创建一个线程,该线程在该方法已经返回后才可以工作。我需要这个线程在一定时间后超时。

我有一个可行的解决方案,但我不确定这是否是最好的方法。

  new Thread(() -> {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<Void> future = executor.submit(new Callable() {
            public Void call() throws Exception {
              workThatTakesALongTime();
        });
        try {
            future.get(timeoutMillis, TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            LOGGER.error("Exception from timeout.", e);
        }
    }).start();

有没有更好的方法来做到这一点,而无需在线程中使用 ExecutorService?

【问题讨论】:

  • 我认为您的解决方案很好。你需要一些东西来完成工作,需要一些东西来安排时间。只使用线程,我猜你会产生一个线程,它会产生另一个线程来处理你的工作。外线程等待一段时间,然后中断内线程。我认为这基本上就是FutureTask 所做的,当您在超时时调用get:hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/…

标签: java multithreading timeout


【解决方案1】:

有多种方法可以做到这一点。 正如您所做的那样,一种方法是使用 ExecutorService。一个更简单的方法是创建一个新线程和一个队列,如果每隔几秒钟就有一些东西,线程就会从中查找。一个例子是这样的:

Queue<Integer> tasks = new ConcurrentLinkedQueue<>();

new Thread(){
    public void run() throws Exception {
        while(true){
            Integer task = null;

            if((task = tasks.poll()) != null){
                // do whatever you want
            }

            Thread.sleep(1000L); // we probably do not have to check for a change that often
        }
    }
}.start();


// add tasks
tasks.add(0);

【讨论】:

    【解决方案2】:

    请参阅允许您传递超时值的ExecutorService.invokeAny() 方法。

    【讨论】:

      猜你喜欢
      • 2021-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-28
      • 2014-03-10
      • 1970-01-01
      • 2022-10-16
      相关资源
      最近更新 更多