选择题
5. 有如下代码:
public static void main(String args[])
{
Threadt=DewThread()
{
public void run()
{
world();
}
};
t.run();
System.out.print("hello");
}
static void world()
{
System.out.print("world");
}
上面程序的运行结果是______。
【正确答案】
B
【答案解析】 Thread类提供了一个start()方法,这个方法的功能是让这个线程开始执行,当开始执行后,JVM将会调用这个线程的run()方法来执行这个线程的任务。如果直接调用run()方法就与调用普通的方法类似。
对于本题而言,首先调用t.run()方法,输出“world”,等调用结束后才会执行System.out.print("hello")语句,输出“hello”。所以,选项B正确。
如果把t.run()改成t.start(),在调用t.start()方法后不需要等这个线程结束,这个方法就会立即返回,然后执行语句System.out.print("Hllo"),在这种情况下,这两个输出语句的执行顺序是无法保证的,任何一个语句都有可能先执行,因此,答案就是选项C。