Java中多线程重复启动


在面试时候经常被问到多线程的相关问题:

今天在测试的时候发现下面的代码会抛出异常: java.lang.IllegalThreadStateException

public static void main(String[] args)throws Exception{
        Test_Thread temp = new Test_Thread();
        Test_Thread temp1 = new Test_Thread();
        Thread t = new Thread(temp);
        Thread t1 = new Thread(temp1);
         
        for(int i=0;i<50;i++){
            if(i%2 == 0){
                t.start();
            } else {
                t1.start();
            }
        }
    }

改成下面这样就可以顺利运行了

public static void main(String[] args)throws Exception{
        Test_Thread temp = new Test_Thread();
        Test_Thread temp1 = new Test_Thread();
    //  Thread t = new Thread(temp);
    //  Thread t1 = new Thread(temp1);
  
        for(int i=0;i<50;i++){
            if(i%2 == 0){
                new Thread(temp).start();
            } else {
                new Thread(temp1).start();
            }
        }
    }

总结:线程不能重复调用start(),也就是说单一线程不能重复启动.


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM