()属于线性超时控制,如果创建多个线程想用它控制所有新线程的执行时间是不可行的。通俗一点说就是该方法中使用的只有一个,即使是在循环中使用了,也只能等其控制完第一个线程之后才能控制后续线程。下面看例子:例子中展示了新创建的9个线程,使用该方法进行超时控制
public static void main(String[] args) throws Exception {
List<Thread> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
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();
// throw new TimeoutException("Thread did not finish within timeout");
list.add(thread);
}
for (Thread o : list) {
TimeUnit.SECONDS.timedJoin(o, 3);
if (o.isAlive()) {
o.interrupt();
throw new TimeoutException("Thread did not finish within timeout");
}
}
}
执行结果如下:
Thread[main,5,main]
Thread[main,5,main]
Thread[main,5,main]
Thread[main,5,main]
Thread[main,5,main]
Thread[main,5,main]
Thread[main,5,main]
Thread[main,5,main]
Thread[main,5,main]
Thread[main,5,main]
Thread[Thread-0,5,main]
Thread[Thread-1,5,main]
Thread[Thread-2,5,main]
Thread[Thread-3,5,main]
Thread[Thread-4,5,main]
Thread[Thread-5,5,main]
Thread[Thread-6,5,main]
Thread[Thread-7,5,main]
Thread[Thread-8,5,main]
Thread[Thread-9,5,main]
Exception in thread "main" java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at com.sinosoft.newstandard.coreservice.controller.test2$1.run(test2.java:26)
at java.lang.Thread.run(Thread.java:748)
java.util.concurrent.TimeoutException: Thread did not finish within timeout
at com.sinosoft.newstandard.coreservice.controller.test2.main(test2.java:52)
任务继续执行..........
任务继续执行..........
任务继续执行..........
任务继续执行..........
任务继续执行..........
任务继续执行..........
任务继续执行..........
任务继续执行..........
任务继续执行..........
Process finished with exit code 1
可见,只有第一个线程被超时控制了,剩下的8个线程都顺利执行完毕!