直接调用Thread对象的 run()方法不会启动单独的线程,而是可以在当前线程中执行。若要从单独的线程中执行Runnable.run,请执行以下任一操作
使用Runnable对象构造一个线程,并在Thread上调用start() 方法。
定义Thread对象的子类,并覆盖其run() 方法的定义。然后构造该子类的实例,并直接在该实例上调用start()方法。
public class ThreadRunMethodTest {
public static void main(String args[]) {
MyThread runnable = new MyThread();
runnable.run(); // Call to run() method does not start a separate thread
System.out.println("Main Thread");
}
}
class MyThread extends Thread {
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("子线程中断。");
}
System.out.println("Child Thread");
}
}
在上面的示例中,主线程ThreadRunMethodTest使用该方法调用子线程MyThreadrun()
。这将导致子线程在执行主线程的其余部分之前运行完毕,以便在“主线程”之前打印“子线程”。
输出结果
Child Thread
Main Thread