zoukankan      html  css  js  c++  java
  • 浅析Thread类run()和start()的区别

    1.先看看jdk文档

    1 void    run()
    2 If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is called; otherwise, this method does nothing and returns.
    1 void    start()
    2 Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.

    线程调用run()方法是直接执行其run方法(正常情况)。

    线程调用start()方法后进入准备状态,等待CPU的调度,当切换到该线程时,线程进入运行状态,执行run()方法。

    既然都是执行线程的run方法,为什么不直接调用run方法?

    2.再看代码

     1 public class Main {
     2 
     3     public static void main(String[] args) {
     4         Mythread t = new Mythread();
     5         Thread thread1 = new Thread(t);
     6         Thread thread2 = new Thread(t);
     7         System.out.println("begin = " + System.currentTimeMillis());
     8         thread1.setName("我是线程1");
     9         thread2.setName("我是线程2");
    10         thread1.run();
    11         thread2.start();
    12         System.out.println("end = " + System.currentTimeMillis());
    13     }
    14 }
    15 
    16 class Mythread extends Thread{
    17     public void run() {
    18         try {
    19             System.out.println("threadName: "+this.currentThread().getName()+" begin");
    20             Thread.sleep(1000);
    21             System.out.println("threadName: "+this.currentThread().getName()+" end");
    22         } catch (InterruptedException e) {
    23             e.printStackTrace();
    24         }
    25     }
    26 }

    运行结果:

    可以发现直接调用run方法时是被主线程当做普通的方法调用,并不是真正的多线程。

    作者: 采采灬卷耳

    <http://www.cnblogs.com/floay/>

    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出, 原文链接 如有问题, 欢迎咨询。

  • 相关阅读:
    【NOIP2007】守望者的逃离
    20200321(ABC)题解 by 马鸿儒 孙晨曦
    20200320(ABC)题解 by 王一帆
    20200319(ABC)题解 by 王一帆 梁延杰 丁智辰
    20200314(ABC)题解 by 董国梁 蒋丽君 章思航
    20200309(ABC)题解 by 梁延杰
    20200307(DEF)题解 by 孙晨曦
    20200306(ABC)题解 by 孙晨曦
    20200305(DEF)题解 by 孙晨曦
    20200303(ABC)题解 by 王锐,董国梁
  • 原文地址:https://www.cnblogs.com/floay/p/6677498.html
Copyright © 2011-2022 走看看