我当时正在阅读来自Multithreading的的完整引用,然后我对这段代码感到震惊,我无法理解这个code.Can的输出--有人帮我做这个吗?
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.");
}
}它产生的输出:
子线程: ThreadDemo线程,5,主线程 主螺纹:5 儿童螺纹:5 儿童线程:4 主线程:4 儿童螺纹:3 儿童线程:2 主螺纹:3 儿童线程:1 退出子线程 主线程:2 主线程:1 主螺纹退出
在main()方法中,调用NewThread()构造函数,然后创建一个名为“演示线程”的Thread类实例,而第一个print()语句得到executed.After,即start()方法是called.Is --这个开始方法不应该隐式调用run()方法,因此应该执行子循环,但是根据主loop.How中的输出,控件可以转到main()循环,即使我们正在调用t.start()?请有人向我说明代码输出给我吗?
发布于 2015-07-12 08:15:30
一旦调用了start(),现在就有两个线程同时运行。start()立即返回,主循环继续(一个循环非常1000mS)。但是子循环现在也在同时运行--每500毫秒就有一个循环。因此,在每个循环完成之前,将为每个主行打印两个子行。
发布于 2015-07-12 08:13:12
除非发生关系之前发生的情况,否则独立线程的执行顺序是不确定的;这使得并发性面临挑战。在调用t.start()之后,t中的主线程和线程之间根本没有任何关系,在系统负载很重的情况下,理论上一个线程或另一个线程可以在控制返回到另一个线程之前按顺序完成所有操作。
https://stackoverflow.com/questions/31365732
复制相似问题