-
Thread中run和start方法的模板设计模式
创建一个Thread需要继承Thread重写run方法或者实现Runnable接口中的run方法,其实两者都是一样因为Thread也继承了Runnable接口。
实现了run方法,但是启动确实用start方法,那么这是为什么?
Thread使用模板设计模式,线程控制的逻辑交给Thread自己,而实现的业务逻辑则交给run方法。
先看一下start方法的一段源码:
1 if (threadStatus != 0) 2 throw new IllegalThreadStateException(); 3 4 group.add(this); 5 6 boolean started = false; 7 try { 8 start0(); 9 started = true; 10 } finally { 11 try { 12 if (!started) { 13 group.threadStartFailed(this); 14 } 15 } catch (Throwable ignore) { 16 /* do nothing. If start0 threw a Throwable then 17 it will be passed up the call stack */ 18 } 19 }
其中run方法是由第8行start0()来启动的。
总的来说就是:run方法来实现自己的业务逻辑,而线程的其他控制逻辑交给Thread,也就是start方法中除了启动run的start0其他逻辑代码则是线程控制的逻辑代码。
来看一个模板方法的例子:
public class TemplateMethodDesign { public final void printMsg(String msg){ System.out.println("System control logic"); customizedMsg(msg); System.out.println("System the other control logic"); } protected void customizedMsg(String msg){ } public static void main(String[] args){ TemplateMethodDesign design = new TemplateMethodDesign(){ @Override public void customizedMsg(String msg) { System.out.println(msg); } }; design.printMsg("here is your logic"); } }
customizedMsg重写自己的逻辑,printMsg方法定义控制的逻辑代码而且是final修饰的,不允许重写。好处就是,结构代码交给父类,子类只需要实现自己的业务逻辑即可。
来源:
https://www.cnblogs.com/niezhichao/p/14239062.html
最新更新
求1000阶乘的结果末尾有多少个0
详解MyBatis延迟加载是如何实现的
IDEA 控制台中文乱码4种解决方案
SpringBoot中版本兼容性处理的实现示例
Spring的IOC解决程序耦合的实现
详解Spring多数据源如何切换
Java报错:UnsupportedOperationException in Col
使用Spring Batch实现批处理任务的详细教程
java中怎么将多个音频文件拼接合成一个
SpringBoot整合ES多个精确值查询 terms功能实
数据库审计与智能监控:从日志分析到异
SQL Server 中的数据类型隐式转换问题
SQL Server中T-SQL 数据类型转换详解
sqlserver 数据类型转换小实验
SQL Server数据类型转换方法
SQL Server 2017无法连接到服务器的问题解决
SQLServer地址搜索性能优化
Sql Server查询性能优化之不可小觑的书签查
SQL Server数据库的高性能优化经验总结
SQL SERVER性能优化综述(很好的总结,不要错
uniapp/H5 获取手机桌面壁纸 (静态壁纸)
[前端] DNS解析与优化
为什么在js中需要添加addEventListener()?
JS模块化系统
js通过Object.defineProperty() 定义和控制对象
这是目前我见过最好的跨域解决方案!
减少回流与重绘
减少回流与重绘
如何使用KrpanoToolJS在浏览器切图
performance.now() 与 Date.now() 对比