1. 程式人生 > >同一個Thread啟動第二次會報錯java.lang.IllegalThreadStateException

同一個Thread啟動第二次會報錯java.lang.IllegalThreadStateException

先實現Thread程式碼

public class TestThread {

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            myThread.start();
            System.out.println(myThread.getName() + "---" + i + "---");
        }

    }

    static Thread myThread = new Thread(new Runnable() {
        int
count = 0; boolean runable = true; public void run() { while (runable) { count++; try { Thread.sleep(100); } catch (Exception e) { } if (count > 100) { runable = false
; } } } }); }

執行結果:

Thread-0---0---
Exception in thread "main" java.lang.IllegalThreadStateException
    at java.lang.Thread.start(Unknown Source)
    at TestThread.main(TestThread.java:6)

當第二次呼叫Thread.start()啟動同一個執行緒時,報錯。

採用Runnable實現,解決問題

public
class TestRunnable { public static void main(String[] args) { for (int i = 0; i < 100; i++) { Thread t = new Thread(myRunnable); t.start(); System.out.println( t.getName() + "---" + i + "---"); } } static Runnable myRunnable = new Runnable() { int count = 0; boolean runable = true; @Override public void run() { while (runable) { count++; try { Thread.sleep(100); } catch (Exception e) { } if (count > 100) { runable = false; } } } }; }

執行結果正常。可以啟動多個執行緒

2016/8/16修改編輯
Thread報錯的原因,並不是說,重新啟動Thread導致的,而是因為共用一個Thread導致的,因為,如果是實現Runnable的類,每次啟動執行緒都需要new Thread(Runnable).start(),這就使得執行緒沒有被共用。所以,另外一種解決辦法是如下:

public class TestThread {

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
//          TestThread t = new TestThread();
            new TThread().start();
//          myThread.start();
//          System.out.println(myThread.getName() + "---" + i + "---");
        }
        Thread.currentThread();

    }   
}

class TThread extends Thread{
    @Override
    public void run() {
        // TODO Auto-generated method stub
        super.run();
        System.out.println("111");
    }
}

只要每次都new 一個新的執行緒物件,就不會報錯。