zoukankan      html  css  js  c++  java
  • 怎么才能记住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  
  • 相关阅读:
    第二阶段站立会议第三天
    第二阶段站立会议第二天
    第二阶段站立会议第一天
    测试计划
    cnblogs用户体验及建议
    第一阶段绩效评估
    第一阶段各组意见回复
    第一阶段团队评价
    站立会议第十天
    站立会议第九天
  • 原文地址:https://www.cnblogs.com/heyt/p/11354940.html
Copyright © 2011-2022 走看看