怎么才能记住java线程的start()和run()谁是启动方法

start()和run()开始的时候总是记不住那个是线程的启动方法,现在是记得很真切了!

如果用run()启动线程就跟不用线程效果是一样的,因为是run是顺序执行的。start()才是线程的启动方法。做了个测试类:

用一个for循环多次,每一次都new一个线程,在构造器中分别start,run好多好多次就出现结果了(重写了toString和super这样结果看起来更直观)。

其实Thread类实现了Runnable接口,run()就是接口里的方法,所以想用run就需要自己重写这个方法。

 1 public class SimpleThread extends Thread {
 2   private int countDown = 5;
 3   private static int threadCount = 0;
 4   public SimpleThread() {
 5     // Store the thread name:
 6     super("第"+Integer.toString(++threadCount)+"条线程: ");
 7     start();
 8     //run();   
 9   }
10   public String toString() {
11     return "#########" + getName() + "执行到第" + countDown + "次 "+"#########";
12   }
13   public void run() {
14     while(true) {
15         System.out.println(this);
16       if(--countDown == 0)
17         return;
18     }
19   }
20   public static void main(String[] args) {
21     for(int i = 0; i < 6; i++) {
22       new SimpleThread();
23     }
24   }
25 } 
26  

 

posted @ 2019-08-14 21:51  篮球是圆的  阅读(745)  评论(0编辑  收藏  举报