如果我们直接调用Java中的run()方法会发生什么?
直接调用 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("Child Thread interrupted."); } System.out.println("Child Thread"); } }登录后复制
输出
Child Thread Main Thread登录后复制