当我们在线程上调用 start() 方法时,它会导致线程开始执行,并且线程的 run() 方法会被调用Java 虚拟机(JVM)。如果我们直接调用 run() 方法,它将被视为线程类(或可运行接口)的正常重写方法,并且它将在当前线程的上下文中执行,而不是在新线程中执行。
public class CallRunMethodTest extends Thread { @Override public void run() { System.out.println("In the run() method: " + Thread.currentThread().getName()); for(int i = 0; i < 5 ; i++) { System.out.println("i: " + i); try { Thread.sleep(300); } catch (InterruptedException ie) { ie.printStackTrace(); } } } public static void main(String[] args) { CallRunMethodTest t1 = new CallRunMethodTest(); CallRunMethodTest t2 = new CallRunMethodTest(); t1.run(); <strong>// calling run() method directly instead of start() method</strong> t2.run(); <strong>// calling run() method directly instead of start() method</strong> } }
在上面的例子中,创建了两个线程,并直接在线程上调用了run()方法,而不是调用start()方法。
In the run() method: main i: 0 i: 1 i: 2 i: 3 i: 4 In the run() method: main i: 0 i: 1 i: 2 i: 3 i: 4
以上就是在Java中,什么时候调用Thread.run()而不是Thread.start()?的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号