怎么才能记住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  

 

转载于:https://www.cnblogs.com/heyt/p/11354940.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值