浅析Thread类run()和start()的区别

1.先看看jdk文档

 void    run()
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.
 void    start()
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.再看代码

 public class Main {

     public static void main(String[] args) {
Mythread t = new Mythread();
Thread thread1 = new Thread(t);
Thread thread2 = new Thread(t);
System.out.println("begin = " + System.currentTimeMillis());
thread1.setName("我是线程1");
thread2.setName("我是线程2");
thread1.run();
thread2.start();
System.out.println("end = " + System.currentTimeMillis());
}
} class Mythread extends Thread{
public void run() {
try {
System.out.println("threadName: "+this.currentThread().getName()+" begin");
Thread.sleep(1000);
System.out.println("threadName: "+this.currentThread().getName()+" end");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

运行结果:

浅析Thread类run()和start()的区别

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

上一篇:谈谈 iOS 中图片的解压缩


下一篇:160803、如何在ES6中管理类的私有数据