前辈们好!问题如下:
有一个线程,给他规定执行用时最大时间,如果他执行的时间超过最大时间,就结束这个线程,代码该怎么写呢,
前辈们给指导指导,谢谢啦
2 回答
慕桂英546537
TA贡献1848条经验 获得超10个赞
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println(Thread.currentThread());
Thread.sleep(6000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
System.out.println(Thread.currentThread());
thread.start();
TimeUnit.SECONDS.timedJoin(thread, 3);
if (thread.isAlive()) {
thread.interrupt();
throw new TimeoutException("Thread did not finish within timeout");
}
TimeUnit
有一个方法 timedJoin
,如果线程未在指定时间运行完,或者指定时间内运行结束,代码会向下走,这时使用 isAlive
判断是否执行结束。
侃侃尔雅
TA贡献1801条经验 获得超16个赞
上面的代码有些问题,并没能真正结束线程。稍微改下就可以了
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println(Thread.currentThread());
Thread.sleep(6000);
} catch (InterruptedException e) {
e.printStackTrace();
**return;**
}
System.out.println("任务继续执行..........");
}
});
System.out.println(Thread.currentThread());
thread.start();
TimeUnit.SECONDS.timedJoin(thread, 3);
if (thread.isAlive()) {
thread.interrupt();
throw new TimeoutException("Thread did not finish within timeout");
}
如果,不加return,将会输出"任务继续执行.........."
添加回答
举报
0/150
提交
取消