解决——》Exception in thread "main" java.lang.IllegalThreadStateException

版权声明:本文为博主原创文章,无需授权即可转载,甚至无需保留以上版权声明,转载时请务必注明作者。
https://blog.csdn.net/weixin_43453386/article/details/88218818

解决——》Exception in thread "main" java.lang.IllegalThreadStateException

    • 1、操作
    • 2、现象(错误信息)
    • 3、原因
    • 4、解决
      • 修改之前的代码
      • 修改过后的代码
IllegalThreadStateException)

1、操作

重复调用线程的start()方法

2、现象(错误信息)

Exception in thread "main" java.lang.IllegalThreadStateException
	at java.lang.Thread.start(Thread.java:708)
	at com.lz.springcloud.xwlvapi.utils.TT.main(TT.java:9)

3、原因

同一个Thread不能重复调用start方法

4、解决

修改之前的代码

public class TT {
    public static void main(String[] args) {
        MyThread m1 = new MyThread("线程A");
        MyThread m2 = new MyThread("线程B");
        MyThread m3 = new MyThread("线程C");
        m1.start();
        m1.start();
        m2.start();
        m3.start();
    }
}
class MyThread extends Thread {
    private String name;


    public MyThread(String name) {
        this.name = name;
    }

    public void run() {
        for (int x = 0; x < 10; x++) {
            System.out.println(this.name + "x=" + x);
        }
    }
}

修改过后的代码

public class TT {
    public static void main(String[] args) {
        MyThread m1 = new MyThread("线程A");
        MyThread m2 = new MyThread("线程B");
        MyThread m3 = new MyThread("线程C");
        m1.start();
        //线程不能重复调用start()方法
        //m1.start();
        m2.start();
        m3.start();
    }
}
class MyThread extends Thread {
    private String name;


    public MyThread(String name) {
        this.name = name;
    }

    public void run() {
        for (int x = 0; x < 10; x++) {
            System.out.println(this.name + "x=" + x);
        }
    }
}

你可能感兴趣的:(Java,java,Thread,exception)