创建一个Thread需要继承Thread重写run方法或者实现Runnable接口中的run方法,其实两者都是一样因为Thread也继承了Runnable接口。

实现了run方法,但是启动确实用start方法,那么这是为什么?

       Thread使用模板设计模式,线程控制的逻辑交给Thread自己,而实现的业务逻辑则交给run方法。

先看一下start方法的一段源码:

  1. 1 if (threadStatus != 0)
  2. 2 throw new IllegalThreadStateException();
  3. 3
  4. 4 group.add(this);
  5. 5
  6. 6 boolean started = false;
  7. 7 try {
  8. 8 start0();
  9. 9 started = true;
  10. 10 } finally {
  11. 11 try {
  12. 12 if (!started) {
  13. 13 group.threadStartFailed(this);
  14. 14 }
  15. 15 } catch (Throwable ignore) {
  16. 16 /* do nothing. If start0 threw a Throwable then
  17. 17 it will be passed up the call stack */
  18. 18 }
  19. 19 }

   其中run方法是由第8行start0()来启动的。

   总的来说就是:run方法来实现自己的业务逻辑,而线程的其他控制逻辑交给Thread,也就是start方法中除了启动run的start0其他逻辑代码则是线程控制的逻辑代码。

  来看一个模板方法的例子:

 

  1. public class TemplateMethodDesign {
  2. public final void printMsg(String msg){
  3. System.out.println("System control logic");
  4. customizedMsg(msg);
  5. System.out.println("System the other control logic");
  6. }
  7. protected void customizedMsg(String msg){
  8. }
  9. public static void main(String[] args){
  10. TemplateMethodDesign design = new TemplateMethodDesign(){
  11. @Override
  12. public void customizedMsg(String msg) {
  13. System.out.println(msg);
  14. }
  15. };
  16. design.printMsg("here is your logic");
  17. }
  18. }

 

 

  1. customizedMsg重写自己的逻辑,printMsg方法定义控制的逻辑代码而且是final修饰的,不允许重写。好处就是,结构代码交给父类,子类只需要实现自己的业务逻辑即可。

 

版权声明:本文为niezhichao原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/niezhichao/p/14239062.html