start和run的区别
run执行的是函数体内容,并没有真正创建线程,star()才创建了线程,并回调了run()方法
public class test extends Thread{
@Override
public void run(){
System.out.println(Thread.currentThread().getName()+"开始学习");
}
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
test test = new test();
test.start();
System.out.println("main线程");
}
}
}执行结果:
main线程
main线程
Thread-0开始学习
main线程
main线程
Thread-1开始学习
main线程
Thread-2开始学习
Thread-3开始学习
main线程
Thread-4开始学习
public class test extends Thread{
@Override
public void run(){
System.out.println(Thread.currentThread().getName()+"开始学习");
}
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
test test = new test();
test.run();
System.out.println("main线程");
}
}
}执行结果:
main开始学习
main线程
main开始学习
main线程
main开始学习
main线程
main开始学习
main线程
main开始学习
main线程
可以看到并没有真正创建线程,并且是以同步的方式运行(即严格按照代码顺序执行)。
start在Thread类中的源码:
public synchronized void start() {
/**
* This method is not invoked for the main method thread or "system"
* group threads created/set up by the VM. Any new functionality added
* to this method in the future may have to also be added to the VM.
*
* A zero status value corresponds to state "NEW".
*/
if (threadStatus != 0)
throw new IllegalThreadStateException();
/* Notify the group that this thread is about to be started
* so that it can be added to the group's list of threads
* and the group's unstarted count can be decremented. */
group.add(this);
boolean started = false;
try {
start0()//start0()真正启动了一个线程
started = true;
} finally {
try {
if (!started) {
group.threadStartFailed(this);
}
} catch (Throwable ignore) {
/* do nothing. If start0 threw a Throwable then
it will be passed up the call stack */
}
}
}



京公网安备 11010502036488号