Java 多线程基础(三) start() 和 run()

时间:2022-05-07 17:03:02

Java 多线程基础(三) start() 和 run()

通过之前的学习可以看到,创建多线程过程中,最常用的便是 Thread 类中的 start() 方法和线程类的 run() 方法。两个方法都包含在 Thread 类中。

一、start() 方法和run() 方法的区别

Thread 类中包含了start() 方法,用于开启一个线程,调用该方法后,线程就进入就绪状态。

run() 方法和普通成员方法一样,可以重复调用。单独调用 run()方法时,会在当前线程执行 run() 方法,而不会启动新的线程。

二、start() 和 run() 的源码(基于JDK 1.8)

start() 方法的源码

public synchronized void start() {
// 如果线程不是"就绪状态",则抛出异常!
if (threadStatus != 0)
throw new IllegalThreadStateException();
// 将线程添加到ThreadGroup中
group.add(this);
boolean started = false;
try {
// start0() 启动线程
start0();
// 设置 started 标记
started = true;
} finally {
try {
if (!started) {
group.threadStartFailed(this);
}
} catch (Throwable ignore) { }
}
}
private native void start0();

start()实际上是通过本地方法start0()启动线程的。而start0()会新运行一个线程,新线程会调用run()方法。

run() 方法的源码

private Runnable target;
public void run() {
  if (target != null) {
    target.run();
  }
}

target是一个Runnable对象。run()就是直接调用Thread线程的Runnable成员的run()方法,并不会新建一个线程。

三、实例

class MyThread extends Thread{
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " is running");
}
}
public class ThreadDemo {
public static void main(String[] args) {
MyThread t1 = new MyThread();
System.out.println(Thread.currentThread().getName() + " MyThread run()");
t1.run();
System.out.println(Thread.currentThread().getName() + " MyThread start()");
t1.start();
}
}