2015-07-12 70 views
0

我是从完全参考阅读多线程,然后我感到震惊这段代码,我无法理解这code.Can某人的输出帮助我?查询有关Java线程

class NewThread implements Runnable 
{ 
    Thread t; 
    NewThread() 
    { 
     t = new Thread(this, "Demo Thread"); 
     System.out.println("Child thread: " + t); 
     t.start(); 
    } 
    public void run() 
    { 
     try 
     { 
      for(int i = 5; i > 0; i--) 
      { 
       System.out.println("Child Thread: " + i); 
       Thread.sleep(500); 
      } 
     } 
     catch (InterruptedException e) 
     { 
      System.out.println("Child interrupted."); 
     } 
     System.out.println("Exiting child thread."); 
    } 
} 
class First 
{ 
    public static void main(String args[]) 
    { 
     new NewThread(); 
     try 
     { 
      for(int i = 5; i > 0; i--) 
      { 
       System.out.println("Main Thread: " + i); 
       Thread.sleep(1000); 
      } 
     } 
     catch (InterruptedException e) 
     { 
      System.out.println("Main thread interrupted."); 
     } 
     System.out.println("Main thread exiting."); 
    } 
} 

它产生的输出:

子线程:螺纹[演示螺纹,如图5所示,主]

主线:5

子线程:5

Child Thread:4

Main主题:4

子线程:3

子线程:2

主线:3

子线程:1

退出子线程

主线:2

主线程:1

主线程退出

从main()方法中,NewThread()调用构造函数,然后Thread类的一个实例被创建名为“演示线”和第一次印刷()语句被执行然后start()方法被调用。这个start方法不应该隐式地调用run()方法,所以应该执行子循环,但是根据输出控制进入主循环。如何控制去main()循环,即使我们调用t.start()?有人可以向我澄清一下代码输出吗?

+1

请注意,这使用非标准间距标准,难以阅读;这种布局(尤其是将开口花括号放在他们自己的路线上)并不能模仿。 – chrylis

+0

@ chrylis-Is现在好吗? –

+0

线程的要点是让事情执行*并发*。启动一个线程执行run()方法,在* another *线程中,它并行*执行到主线程。主线程不会等待新线程完成,否则,启动线程将毫无用处。 –

回答

1

除非有发生之间的关系,独立线程的执行顺序是非确定性的;这是什么让并发具有挑战性。在调用t.start()之后,主线程和t中的线程之间完全没有关系,并且在系统负载很重的情况下,一个线程或另一个线程理论上可以在控制返回到其他线程之前完成所有的顺序在所有。

3

一旦start()被调用,现在有两个线程同时运行。 start()立即返回并且主循环继续(一个循环非常1000mS)。但儿童循环现在也在同一时间运行 - 每500mS一个循环。因此,直到每个循环结束,都会为每条主线打印两条子线。