【问题标题】:Why is my thread executing last even though I have put call to start first? [duplicate]为什么我的线程最后执行,即使我已经先调用开始? [复制]
【发布时间】:2019-12-07 13:44:41
【问题描述】:
class test1 extends Thread  
{ 
   public void run() 
   { 
       System.out.println("Run method executed by child Thread"); 
   } 
   public static void main(String[] args) 
   { 
       test1 t = new test1(); 
       t.start();
       System.out.println(726*656); 
       System.out.println("Main method executed by main thread"); 
   } 
}


输出是 -

476256

Main method executed by main thread
Run method executed by child Thread

为什么即使我先调用 start 方法,线程语句也会最后出现

【问题讨论】:

  • 它不会总是生成相同的输出,因为Thread 不保证它。尝试多次运行程序,输出会改变
  • 如果你想要顺序输出,那么使用两个线程是没有意义的。在这种情况下,只需在主线程上执行所有操作。

标签: java multithreading


【解决方案1】:

当你调用 start 时,新线程开始执行,但它不影响已经在执行的 Main 线程。如果您希望主线程等待新线程,您可以在新线程上调用诸如“join”之类的方法来等待它完成

【讨论】:

    猜你喜欢
    • 2011-04-20
    • 2016-09-06
    • 1970-01-01
    • 1970-01-01
    • 2022-11-30
    • 2021-12-05
    • 2020-03-15
    • 2011-01-03
    • 1970-01-01
    相关资源
    最近更新 更多