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修饰的,不允许重写。好处就是,结构代码交给父类,子类只需要实现自己的业务逻辑即可。