java.lang.IllegalThreadStateException

本文深入分析了Java多线程并发中出现的常见错误——启动已死亡线程的问题,并提供了修正方法。通过实例代码演示,阐述了线程状态与操作之间的关系,帮助开发者理解并避免此类错误,提升程序的稳定性和性能。
public class Threads4 {
    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();
    }
}

运行结果:
Exception in thread "main" java.lang.IllegalThreadStateException
    at java.lang.Thread.start(Unknown Source)
foo    at module_01.q021.utils.Threads4.go(Threads4.java:17)
    at module_01.q021.utils.Threads4.main(Threads4.java:6)
---------------------------------------------------------------------------
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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值