简体   繁体   English

如何设置线程超时

[英]How to set thread timeout

I have this scala code, which works just fine ( run() is overridden in class) 我有这个scala代码,它很好用(在类中重写run()

val processRunnable = new myProcessClassWithOverriddenRunFunction()
val processThread = new Thread(processRunnable)
processThread.start

What I want to do is set a timeout for processThread thread. 我想做的是为processThread线程设置超时 How can I do that? 我怎样才能做到这一点?

I did some research and couldn't find any parameter we can pass to new Thread() or any function in processThread to achieve that. 我做了一些研究,找不到可以传递给new Thread()processThread任何函数来实现这一点。

Found some solutions on stackoveflow which implemented a ExecutorService but unfortunately, that is not implementable in this particular problem as making another new ExecutorService for just a single processThread , everytime this function is called seems inefficient. 上找到一些解决方案stackoveflow其实施的ExecutorService ,但不幸的是,这是不是在这个特殊的问题,因为制作另一个新实施的ExecutorService只是一个单一的processThread ,每次调用该函数似乎效率不高。 There are some other reasons as well but my question is how can I implement that functionality on this code? 还有其他一些原因,但是我的问题是如何在此代码上实现该功能?

There is no way to achieve that without the thread cooperating. 没有线程的协作就无法实现这一目标。 This is similar in nature to how to make a thread interruptible , and has to do with the fact that it is in general unsafe to stop running threads asynchronously (and a timeout is asynchronous). 这本质上类似于如何使线程可中断 ,并且与以下事实有关:通常,异步停止运行线程是不安全的 (并且超时是异步的)。

Your thread needs to include the timeout capability as part of it's implementation, so that it can act on a timeout condition when it is safe for it to do so. 您的线程需要在其实现中包括超时功能,以便在安全的情况下可以在超时条件下执行操作。

For example: 例如:

public class MyProcessClass {
    private final long timeoutMillis = 30000;
    public void run() {
        long timeout = System.currentTimeMillis() + timeoutMillis;
        while (System.currentTimeMillis() < timeout) {
            // Process next chunk of work
        }
    }
}

PS. PS。 Don't be misled by the other answer based on the ExecutorService - it requires the thread to be interruptible, ie the same solution as shown above. 不要被基于ExecutorService其他答案所误导-它要求线程是可中断的,即与上面所示的解决方案相同。

        while (!Thread.interrupted()) {
            // Process next chunk of work
        }

In Java, you can use 在Java中,您可以使用

CompletableFuture<Void> future = CompletableFuture.runAsync(processRunnable);
future.get(1000, TimeUnit.MILLISECONDS);

To future.get function will throw a TimeOutException when timeout (1 second in the example above) is reached and the timeout case can be handled in catch block. 对于future.get函数,当达到超时(在上面的示例中为1秒)并且可以在catch块中处理超时情况时,将抛出TimeOutException
Complete code will be something like this: 完整的代码如下所示:

try {
     CompletableFuture<Void> future = CompletableFuture.runAsync(processRunnable);
    future.get(1000, TimeUnit.MILLISECONDS);
}
catch{
case texc : TimeoutException => println("Timeout is reached.")
case exc  : Exception => println(exc.getmessage)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM