我是从完全参考阅读多线程,然后我感到震惊这段代码,我无法理解这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()?有人可以向我澄清一下代码输出吗?
请注意,这使用非标准间距标准,难以阅读;这种布局(尤其是将开口花括号放在他们自己的路线上)并不能模仿。 – chrylis
@ chrylis-Is现在好吗? –
线程的要点是让事情执行*并发*。启动一个线程执行run()方法,在* another *线程中,它并行*执行到主线程。主线程不会等待新线程完成,否则,启动线程将毫无用处。 –