Thread的start()方法
public synchronized void start() {
// 如果线程不是"就绪状态",则抛出异常!
if (threadStatus != 0)
throw new IllegalThreadStateException();
// 将线程添加到ThreadGroup中
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 */
}
}
}
说明:
start()实际上是通过本地方法start0()启动线程的。而start0()会新运行一个线程,新线程会调用run()方法。
Thread的run()方法
@Override
public void run() {
if (target != null) {
target.run();
}
}
说明:
target是一个Runnable对象。run()就是直接调用Thread线程的Runnable成员的run()方法,并不会新建一个线程。
示例
public class MyThread extends Thread{
public MyThread(String name){
super(name);
}
public void run() {
System.out.println(Thread.currentThread().getName() + " is running.");
}
public static void main(String[] args) {
MyThread myThread = new MyThread("myThread");
System.out.println(Thread.currentThread().getName() + " call myThread.run()");
//在当前线程中运行myThread的run()方法
myThread.run();
System.out.println(Thread.currentThread().getName() + " call myThread.start()");
//启动一个新线程,并在新线程中运行run()方法
myThread.start();
}
}
运行结果
main call myThread.run() //主线程调用run()方法
main is running. //执行run()方法,不会创建新的线程
main call myThread.start() //主线程通过start()方法启动新的线程
myThread is running. // 新线程的start方法会调用run()方法