java如何关闭一个线程_如何关闭一个java线程池
Java 并發工具包中 java.util.concurrent.ExecutorService 接口定義了線程池任務提交、獲取線程池狀態、線程池停止的方法等。
JDK 1.8 中,線程池的停止一般使用 shutdown()、shutdownNow()方法。
shutdown有序關閉,已提交任務繼續執行
不接受新任務
主線程向線程池提交了 10 個任務,休眠 4 秒后關閉線程池,線程池把 10 個任務都執行完成后關閉了。
public static void main(String[] args) {
//創建固定 3 個線程的線程池
ExecutorService threadPool = Executors.newFixedThreadPool(3);
//向線程池提交 10 個任務
for (int i = 1; i <= 10; i++) {
final int index = i;
threadPool.submit(() -> {
System.out.println("正在執行任務 " + index);
//休眠 3 秒
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
//休眠 4 秒
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//關閉線程池
threadPool.shutdown();
}
shutdownNow嘗試停止所有正在執行的任務
停止等待執行的任務,并返回等待執行的任務列表
主線程向線程池提交了 10 個任務,休眠 4 秒后關閉線程池,線程池執行了數個任務后拋出異常,打印返回的剩余未執行的任務個數。
public static void main(String[] args) {
//創建固定 3 個線程的線程池
ExecutorService threadPool = Executors.newFixedThreadPool(3);
//向線程池提交 10 個任務
for (int i = 1; i <= 10; i++) {
final int index = i;
threadPool.submit(() -> {
System.out.println("正在執行任務 " + index);
//休眠 3 秒
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
//休眠 4 秒
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//關閉線程池
List tasks = threadPool.shutdownNow();
System.out.println("剩余 " + tasks.size() + " 個任務未執行");
}
判斷線程池是否關閉awaitTermination收到關閉請求后,所有任務執行完成、超時、線程被打斷,阻塞直到三種情況任意一種發生
參數可以設置超時時間于超時單位
線程池關閉返回 true;超過設置時間未關閉,返回 false
public static void main(String[] args) {
//創建固定 3 個線程的線程池
ExecutorService threadPool = Executors.newFixedThreadPool(3);
//向線程池提交 10 個任務
for (int i = 1; i <= 10; i++) {
final int index = i;
threadPool.submit(() -> {
System.out.println("正在執行任務 " + index);
//休眠 3 秒
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
//關閉線程池,設置等待超時時間 3 秒
System.out.println("設置線程池關閉,等待 3 秒...");
threadPool.shutdown();
try {
boolean isTermination = threadPool.awaitTermination(3, TimeUnit.SECONDS);
System.out.println(isTermination ? "線程池已停止" : "線程池未停止");
} catch (InterruptedException e) {
e.printStackTrace();
}
//再等待超時時間 20 秒
System.out.println("再等待 20 秒...");
try {
boolean isTermination = threadPool.awaitTermination(20, TimeUnit.SECONDS);
System.out.println(isTermination ? "線程池已停止" : "線程池未停止");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
shutdown和shutdownNow的異同調用 shutdown() 和 shutdownNow() 方法關閉線程池,線程池都無法接收新的任務。
shutdown() 方法會繼續執行正在執行未完成的任務,shutdownNow() 方法會嘗試停止所有正在執行的任務。
shutdown() 方法沒有返回值,shutdownNow() 方法返回等待執行的任務列表。
awaitTermination(long timeout, TimeUnit unit) 方法可以獲取線程池是否已經關閉,需要配合 shutdown() 使用。
shutdownNow() 不一定能夠立馬結束線程池,該方法會嘗試停止所有正在執行的任務,通過調用 Thread.interrupt() 方法來實現的,如果線程中沒有 sleep() 、wait()、Condition、定時鎖等應用,interrupt() 方法是無法中斷當前的線程的。
總結
以上是生活随笔為你收集整理的java如何关闭一个线程_如何关闭一个java线程池的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 51单片机外部中断实验 设置中断优先级
- 下一篇: getordefault java_Ja