如果我们直接调用 Java 中的 run() 方法会发生什么?
javaobject oriented programmingprogramming更新于 2024/7/25 21:16:00
直接调用 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"); } }
在上面的例子中,主线程 ThreadRunMethodTest 使用 run() 方法调用子线程 MyThread。这会导致子线程在主线程的其余部分执行之前运行完成,因此"Child Thread"在"Main Thread"之前打印。
输出
Child Thread Main Thread