【发布时间】:2018-01-10 23:06:06
【问题描述】:
我正在阅读 Java 中的线程,并通过实现 Runnable 接口并使用 start() 和 run() 函数来创建一个新线程。
我的代码如下:
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);
t.sleep(500);
}
}
catch(InterruptedException e)
{
System.out.println("Exception Caught!");
}
System.out.println("Exiting child thread!");
}
}
class Threads
{
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("Exception caught!");
}
System.out.println("Exiting main thread!");
}
}
从main函数的第一行开始,调用NewThread类的构造函数。
我读到的是
新线程创建后,它不会开始运行,直到你 调用它的 start() 方法,该方法在 Thread 中声明。在本质上, start( ) 执行对 run( ) 的调用
那为什么主线程在 start() 被调用后才运行,而子线程即 run() 函数却没有呢?
以下是输出:
C:\Users\Kaustubh Srivastava\Desktop\Java\Test>java Threads
Child Thread: Thread[Demo Thread,5,main]
Main thread: 5
Child Thread: 5
Child Thread: 4
Main thread: 4
Child Thread: 3
Child Thread: 2
Main thread: 3
Child Thread: 1
Exiting child thread!
Main thread: 2
Main thread: 1
Exiting main thread!
【问题讨论】:
-
你在它的构造函数中调用了线程的
start,所以它的run()被立即执行。 -
但是根据输出结果不对?
-
好的,“立即”是错误的词。一旦轮到新启动的线程运行,打印就会发生,这可能是在从构造函数返回之前或之后。
-
好的,知道了。谢谢你:)
-
从线程可以看到的对象的构造函数中启动线程是错误的。 stackoverflow.com/a/5623327/801894
标签: java multithreading runnable