設(shè)定一個(gè)線程最多運(yùn)行3秒 超過3秒就中斷 兩種方法
1.用Future
final ExecutorService exec = Executors.newFixedThreadPool(1);
Future<Object> future = exec.submit(() -> {
for (int i = 1; i <= 1000; i++) {
System.out.println(i + "");
Thread.sleep(1000L);
}
return null;
});
try {
future.get(3000, TimeUnit.MILLISECONDS);
} catch (Exception e) {
e.printStackTrace();
future.cancel(true);//必須代碼
}
System.out.println("end");
2.Thread.interrupt (嚴(yán)格來說沒啥用 因?yàn)檎5倪壿嫶a中不會(huì)有Thread.sleep())
Thread t1 = new Thread(() -> {
for (int i = 1; i <= 1000; i++) {
System.out.println(i + "");
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
throw new RuntimeException(e); //必須拋出異常 不然還是會(huì)繼續(xù)執(zhí)行
}
}
});
t1.start();
try {
t1.join(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
t1.interrupt(); //核心代碼
System.out.println("end");
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者