public class Threads4 {
}
运行结果:
Exception in thread "main" java.lang.IllegalThreadStateExcept ion
foo at module_01.q021.utils.Threads4.go(Threads4.java:17)
---------------------------------------------------------------------------
Thrown to indicate that a thread is not in an appropriate state for the requested operation. See, for example, the suspend
and resume methods in class Thread.
-------------------------------------------
对于一个已经死亡的线程调用start,sleep之类的操作等。
因此,上面代码中,应该去掉一个 t.start() ,就 OKAY 啦
---------------------------------------------------------------------------------
请对比下面这一题:
Given:
1. public class Threads3 implements Runnable {
2. public void run() {
3. System.out.print("running");
4. }
5. public static void main(String[] args) {
6. Thread t = new Thread(new Threads3());
7. t.run();
8. t.run();
9. t.start(); //注意:此处只调用了一次start(),故不会出现上面一题的异常
10. }
11. }
What is the result?
A. Compilation fails.
B. An exception is thrown at runtime.
C. The code executes and prints "running".
D. The code executes and prints "runningrunning".
E. The code executes and prints "runningrunningrunning".
Answer: E
本文深入分析了Java多线程并发中出现的常见错误——启动已死亡线程的问题,并提供了修正方法。通过实例代码演示,阐述了线程状态与操作之间的关系,帮助开发者理解并避免此类错误,提升程序的稳定性和性能。
873

被折叠的 条评论
为什么被折叠?



