你真的了解多线程吗?

      作为一个有多年Java开发经验的老鸟,你知道在Java中创建线程的方式有几种吗?你在搜索引擎中输入“Java线程 创建方式”这个关键字,内容层出不穷,有2种的、3种的甚至还有6种的。他们说的都对吗?你有没有对网络上的内容做一下自己的判断呢?

  其实Java中创建线程有2种方式。我们可以打开JDK 8中Thread类的源代码,里面的注释,清晰的写明了这一点。以下是我从源码注释中截取出来的部分。

/**
   *There are two ways to create a new thread of execution. One is to declare a class to be a subclass of Thread. This subclass should override the run method 
   *of class Thread. An instance of the subclass can then be allocated and started. 
   *The other way to create a thread is to declare a class that implements the Runnable interface. That class then implements the run method. An instance of 
   *the class can then be allocated, passed as an argument when creating Thread,and started.
   */

  这篇注释解释了第一种方式是可以通过继承的方式,声明一个Thread类的子类,然后重写Thread类的run方法,创建一个线程。第二种方式,声明一个实现Runnable接口的实现类,在这个实现类中实现run方法,然后当创建一个Thread对象时,把这个实现Runnable接口的实现类,以参数的形式传入Thread对象中,从而完成一个Thread对象创建。

posted @ 2021-06-03 15:44  夏日彩虹  阅读(71)  评论(0)    收藏  举报