5.
【知识点】
(1)Thread类的start()方法
start()方法用于启动线程的执行,也就是让run()方法开始运行。
start()方法只允许执行一次,也就是说一个线程只允许启动一次,即使执行完毕也不允许重新启动,否则会抛出IllegalThreadStateException。
【例题】
public static void main(String[] args) {
new Threads4().go();
}
public void go() {
Runnable r = new Runnable() {
public void run() {
System.out.print("foo");
}
};
Thread t = new Thread(r);
t.start();
t.start();
}
}
What is the result?
A. Compilation fails.
B. An exception is thrown at runtime.
C. The code executes normally and prints "foo".
D. The code executes normally, but nothing is printed.
【Answer】 B
【例题辨析】
A. 可以在Eclipse开发环境中尝试录入本程序,如果编辑窗口中没有错误提示出现,通常不存在编译错误;
B. 同样,在Eclipse开发环境中尝试录入本程序,可以看到如下信息:
fooException in thread "main"java.lang.IllegalThreadStateException
atjava.lang.Thread.start(Unknown Source)
atThreads4.go(Threads4.java:17)
atThreads4.main(Threads4.java:5)
上述信息说明运行时抛出了异常,这是因为Thread类的start()方法只允许执行一次,也就是说一个线程只允许启动一次,即使执行完毕也不允许重新启动;
C. 同上
D. 同上