Thread的start方法—模板模式

一、模板模式Demo

1、需求

比如打印机,有的型号能打印全部东西,有的却只能打印普通文字。

2、代码

public abstract class TemplateMethod {

   public final void print() {
       wrapPrint();
  }

   protected abstract void wrapPrint();

   public static void main(String[] args) {
       new TemplateMethod() {
           @Override
           protected void wrapPrint() {
               System.out.println("我能输出任何东西");
          }
      }.wrapPrint();

       new TemplateMethod() {
           @Override
           protected void wrapPrint() {
               System.out.println("我只能输出普通文字");
          }
      }.wrapPrint();
  }
}

有没有发现和Thread神似,那就对了,继续往下看。

二、start方法的模板

1、疑问

我起线程已经重写run方法了为什么还需要单独执行start方法才能运行呢?

2、解疑

2.1、start方法注释

/**
* Causes this thread to begin execution; the Java Virtual Machine
* calls the <code>run</code> method of this thread.
* <p>
* The result is that two threads are running concurrently: the
* current thread (which returns from the call to the
* <code>start</code> method) and the other thread (which executes its
* <code>run</code> method).
* <p>
* It is never legal to start a thread more than once.
* In particular, a thread may not be restarted once it has completed
* execution.
*
* @exception IllegalThreadStateException if the thread was already started.
* @see       #run()
* @see       #stop()
*/
public synchronized void start() {}

2.2、解释

前两句注释已经给予了答案:

Causes this thread to begin execution; the Java Virtual Machine
calls the <code>run</code> method of this thread.
使该线程开始执行; Java虚拟机调用此线程的run方法</pre>

粗糙理解为:start方法会调用run方法。

所以我们起线程都会重写run方法并调用start方法。相当于我们重写run方法不调用start方法,那就跟你new了一个普通类没任何区别。

new Thread() {
   @Override
   public void run() {
       // 。。。
  }
}.start();

new Thread() {
   @Override
   public void run() {
       // 。。。
  }
}.start()

2.3、注意

说他是模板模式也算是,但又不算是。因为他的start方法可以被重写,并没有被final修饰。重写后就不会调用run方法了。

解释一下为什么不会调用run了,因为真正调用run方法的是Thread里的这个私有的start方法

private native void start0();,虚拟机会调用这个方法,这个native方法会触发run方法。注意他是私有的,所以你重写start方法的时候内部是无法调用start0的,自然也就不会调用run了。

有人又问:那我可以重写start方法,在重写的start方法内部自行调用run方法,我只能说确实可以,但是这不是一个线程,执行这个方法的还是main线程,而不是你自己new的Thread。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容