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