做网站的基础架构,沧州建网站,企业高端网站建设需要注意哪些事项,软文网站推荐Java 并发工具包中 java.util.concurrent.ExecutorService 接口定义了线程池任务提交、获取线程池状态、线程池停止的方法等。JDK 1.8 中#xff0c;线程池的停止一般使用 shutdown()、shutdownNow()方法。shutdown有序关闭#xff0c;已提交任务继续执行不接受新任务主线程向…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超过设置时间未关闭返回 falsepublic 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() 方法是无法中断当前的线程的。