Java线程池用法实战案例分析
作者:cakincqm 时间:2022-01-22 07:57:16
本文实例讲述了Java线程池用法。分享给大家供大家参考,具体如下:
一 使用newSingleThreadExecutor创建一个只包含一个线程的线程池
1 代码
import java.util.concurrent.*;
public class executorDemo
{
public static void main( String[] args )
{
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(() -> {
String threadName = Thread.currentThread().getName();
System.out.println("Hello " + threadName);
});
}
}
2 运行
Hello pool-1-thread-1
二 含有终止方法的线程池
1 代码
import java.util.concurrent.*;
public class executorShutdownDemo {
public static void main( String[] args ) {
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(() -> {
String threadName = Thread.currentThread().getName();
System.out.println("Hello " + threadName);
});
try {
TimeUnit.SECONDS.sleep(3);
System.out.println("尝试关闭线程执行器...");
executor.shutdown();
executor.awaitTermination(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
System.err.println("关闭任务被中断!");
} finally {
if (!executor.isTerminated()) {
System.err.println("取消未完成的任务");
executor.shutdownNow();
}
System.out.println("任务关闭完成");
}
}
}
2 运行
Hello pool-1-thread-1
尝试关闭线程执行器...
任务关闭完成
3 说明
shutdown只是将线程池的状态设置为SHUTWDOWN状态,正在执行的任务会继续执行下去,没有被执行的则中断。
shutdownNow则是将线程池的状态设置为STOP,正在执行的任务则被停止,没被执行任务的则返回。
举个工人吃包子的例子:一个厂的工人(Workers)正在吃包子(可以理解为任务)。
假如接到shutdown的命令,那么这个厂的工人们则会把手头上的包子给吃完,没有拿到手里的笼子里面的包子则不能吃!
而如果接到shutdownNow的命令以后呢,这些工人们立刻停止吃包子,会把手头上没吃完的包子放下,更别提笼子里的包子了。
awaitTermination(long timeOut, TimeUnit unit)
当前线程阻塞,直到
等所有已提交的任务(包括正在跑的和队列中等待的)执行完
或者等超时时间到
或者线程被中断,抛出InterruptedException
然后返回true。
更多java相关内容感兴趣的读者可查看本站专题:《Java进程与线程操作技巧总结》、《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》、《Java文件与目录操作技巧汇总》和《Java缓存操作技巧汇总》
希望本文所述对大家java程序设计有所帮助。
来源:https://blog.csdn.net/chengqiuming/article/details/95889219
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Spring Boot集成Spring Cache过程详解
![](https://img.aspxhome.com/file/2023/3/84583_0s.png)
java类中生成jfreechart,返回图表的url地址 代码分享
struts2简介_动力节点Java学院整理
![](https://img.aspxhome.com/file/2023/3/72323_0s.jpg)
sms4j 2.0 全新来袭功能的调整及maven变化详解
使用注解@Recover优化丑陋的循环详解
![](https://img.aspxhome.com/file/2023/0/80880_0s.png)
Java TreeSet类的简单理解和使用
![](https://img.aspxhome.com/file/2023/2/77952_0s.jpg)
Spring中BeanFactory与FactoryBean接口的区别详解
![](https://img.aspxhome.com/file/2023/1/66501_0s.jpg)
深入浅析Java反射机制
java使用OGEngine开发2048
Java SpringBoot高级用法详解
![](https://img.aspxhome.com/file/2023/8/62998_0s.png)
学习使用Material Design控件(一)
![](https://img.aspxhome.com/file/2023/3/84743_0s.jpg)
C#网络编程基础之进程和线程详解
![](https://img.aspxhome.com/file/2023/7/78147_0s.png)
JAVA内存模型(JMM)详解
![](https://img.aspxhome.com/file/2023/5/59975_0s.png)
C#集合查询Linq在项目中使用详解
Java微信公众平台开发(13) 微信JSSDK中Config配置
![](https://img.aspxhome.com/file/2023/9/67439_0s.jpg)
Android 获取判断是否有悬浮窗权限的方法
java自定义封装StringUtils常用工具类
C#实现GZip压缩和解压缩入门实例
Android仿google now效果的呼吸按钮
![](https://img.aspxhome.com/file/2023/4/91034_0s.gif)