共計(jì) 803 個(gè)字符,預(yù)計(jì)需要花費(fèi) 3 分鐘才能閱讀完成。
在 Java 中實(shí)現(xiàn)線程超時(shí)自動(dòng)關(guān)閉可以使用兩種方式:使用 Timer 類或使用 Future 接口。
- 使用 Timer 類:
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
// 線程超時(shí)時(shí)關(guān)閉線程
thread.interrupt(); // thread 為要關(guān)閉的線程}
}, timeout);
Thread thread = new Thread() {
@Override
public void run() {// 線程邏輯代碼}
};
thread.start();
在上述代碼中,使用 Timer 類創(chuàng)建一個(gè)定時(shí)器,在指定的超時(shí)時(shí)間后調(diào)用 TimerTask 的 run 方法,從而執(zhí)行線程的中斷操作。
- 使用 Future 接口:
ExecutorService executor = Executors.newSingleThreadExecutor();
Future future = executor.submit(new Runnable() {
@Override
public void run() {// 線程邏輯代碼}
});
try {future.get(timeout, TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {// 超時(shí)異常處理} finally {future.cancel(true);
executor.shutdown();}
在上述代碼中,使用 ExecutorService 創(chuàng)建一個(gè)線程池,通過(guò) submit 方法提交一個(gè) Runnable 任務(wù)并返回一個(gè) Future 對(duì)象。然后使用 future.get 方法設(shè)置超時(shí)時(shí)間,如果任務(wù)在指定時(shí)間內(nèi)未完成,則拋出 TimeoutException 異常,可以在 catch 塊中進(jìn)行超時(shí)異常處理。最后,使用 future.cancel 方法取消任務(wù)并關(guān)閉線程池。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完