gpt4 book ai didi

java - 如果线程在设定的时间段后尚未完成,这是停止线程的正确方法吗?

转载 作者:行者123 更新时间:2023-12-02 02:33:41 26 4
gpt4 key购买 nike

public class TimeToDieThread extends Thread implements Runnable
{
private Runnable r;
private long lTimeLength;//time NanoTime

public TimeToDieThread(Runnable r, long lTimeLength)
{
super();
this.r = r;
this.lTimeLength = lTimeLength;
}
public void start() {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
boolean bran = false;
while ((!Thread.currentThread().isInterrupted()) && (bran == false)) {
r.run();
bran = true;
}
}
});
t.start();
// Sleep a for entire length, and then interrupt
try
{
Thread.sleep(lTimeLength);
} catch (InterruptedException e)
{
System.out.println("Interrupted, wop wop waa");
}
t.interrupt();
}
}

最佳答案

很少需要直接使用Thread(并且绝对没有必要扩展Thread并实现Runnable,因为Thread 已经实现了 Runnable)。

使用 ExecutorService,向其提交一个 Runnable,然后在返回的 上使用 get(long, TimeUnit) 方法Future 等待它完成。

// Construct this somewhere. Note that you also need to shut it down somewhere.
// This is just an example of how you might construct it; other executors are
// available.
ExecutorService executorService = Executors.newFixedThreadPool(nThreads);

Future<?> future = executorService.submit(yourRunnable);
future.get(timeout, timeoutUnit); // Exception handling omitted.
// Cancel if it is still running.
future.cancel(true);

关于java - 如果线程在设定的时间段后尚未完成,这是停止线程的正确方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46717921/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com