查询java中的线程

时间:2015-07-12 08:06:17

标签: java multithreading

我正在从完整参考阅读多线程,然后我对此代码感到震惊,我无法理解此代码的输出。有人可以帮助我此?

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

     

Child Thread:5

     

Child Thread:4

     

主线程:4

     

Child Thread:3

     

Child Thread:2

     

主线程:3

     

Child Thread:1

     

退出子线程

     

主线程:2

     

主线程:1

     

主线程退出

从main()方法调用NewThread()构造函数,然后创建一个名为“demo thread”的Thread类实例,并执行第一个print()语句。之后调用start()方法。这个启动方法不应该隐式调用run()方法,因此应该执行子循环,但根据输出,控件进入主循环。控件如何转到main()循环,即使我们正在调用t.start()?有人可以请求代码输出给我吗?

2 个答案:

答案 0 :(得分:3)

调用start()后,现在有两个线程同时运行。 start()立即返回,主循环继续(一个循环非常1000mS)。但是,子循环现在也在同一时间运行 - 每500毫秒一个循环。因此,在每个循环结束之前,将为每条主线打印两个子行。

答案 1 :(得分:1)

除非发生在关系之前,否则独立线程的执行顺序是不确定的;这就是并发性的挑战。在调用t.start()之后,主线程与t中的线程之间根本没有任何关系,并且在不太可能的情况下系统负载很重,一个线程或另一个线程可以理论上,在控制返回到另一个线程之前按顺序完成所有。