直接调用 Thread 对象的 run() 方法不会启动单独的线程,并且可以在当前线程内执行。要从单独的线程中执行 Runnable.run,请执行以下操作之一
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。这会导致子线程在主线程的其余部分执行之前运行完成,以便在“Main Thread”之前打印“Child Thread”。
Child Thread Main Thread
以上就是如果我们直接调用Java中的run()方法会发生什么?的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号