猿问

创建线程已经返回后如何在 Java 线程处超时?

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


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


  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 ?


神不在的星期二
浏览 124回答 2
2回答

ABOUTYOU

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

九州编程

有多种方法可以实现这一点。正如您所做的那样,一种方法是使用 ExecutorService。一个更简单的方法是创建一个新线程和一个队列,如果每隔几秒就有一些东西,线程就会从中查找。一个例子是这样的:Queue<Integer> tasks = new ConcurrentLinkedQueue<>();new Thread(){&nbsp; &nbsp; public void run() throws Exception {&nbsp; &nbsp; &nbsp; &nbsp; while(true){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Integer task = null;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if((task = tasks.poll()) != null){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // do whatever you want&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Thread.sleep(1000L); // we probably do not have to check for a change that often&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}.start();// add taskstasks.add(0);
随时随地看视频慕课网APP

相关分类

Java
我要回答