2011-05-26 86 views
0

我有一個按鈕的主窗體,按下時,應該啓動一個新的倒計時器線程。Thread.sleep暫停整個程序

這是該按鈕的動作監聽器代碼:

Counter c = new Counter(timeToFinish); 

這是Counter類代碼:

class Counter implements Runnable { 

     int waitingTime = 0; 
     Thread myCounter = new Thread(this); 

     public Counter(int waitingTime) 
     { 
      this.waitingTime = waitingTime; 
      myCounter.run(); 
     } 

     public void run(){ 

      //Start countdown: 
      do 
      { 

       waitingTime -= 1; 

       try { 

        Thread.sleep(1000); 
        System.out.println(waitingTime); 
       } catch (InterruptedException e) { 
        e.printStackTrace(); 
       } 
      } while (waitingTime >= 0); 

     } 
    } 

的問題是,當我創建了計數器的新實例它會暫停整個程序,而不僅僅是那個線程!該問題必須與「Thread.sleep」。

+0

爲什麼程序暫停?是因爲當前線程是UI線程嗎?通常主線程應該通過每個計數器停留1秒來運行? – ssinganamalla 2014-03-13 05:06:51

回答

6

因爲您直接調用運行方法。

相反,你應該把它包裝在一個線程中並啓動線程。

對於例如,更換

myCounter.run(); 

通過

new Thread(this).start(); 
-1

您應該使用SwingUtilities類

看到

http://www.java2s.com/Code/Java/Threads/InvokeExampleSwingandthread.htm

// Report the result using invokeLater(). 
    SwingUtilities.invokeLater(new Runnable() { 
     public void run() { 
     resultLabel.setText("Ready"); 
     setEnabled(true); 
     } 
    }); 
    } 
}; 
+1

甚至沒有提到Swing。 – jzd 2011-05-26 11:36:01

+0

他用一個按鈕提到了一個表單,這可能表明這是一個GUI程序。 – Dikei 2011-05-26 11:37:21

+0

是的,你是對的。我的錯。 – fmucar 2011-05-26 12:38:34

1

您實際上並不是start() ing多個線程。

Thread.run()方法只是運行與線程相關的代碼,就像任何其他常規函數一樣。它不會啓動一個單獨的線程。

您需要致電Thread.start(),啓動一個新線程並在其中運行您的代碼。

3

僅僅因爲您從Counter構造函數調用run方法。這不是它如何與線程一起工作。你必須去掉這個調用,在Thread例如包裹Runnable和線程調用start()

new Thread(new Counter(2)).start(); 
0

你應該用你的線程start()方法。使用

c.start(); 

否則,你有一個類和要調用其方法之一,當然它是在主線程中運行,並睡在主線程。

0

你調用直接運行,它會在當前線程中運行,並睡眠當前線程,我猜是事件線程。這會導致程序暫停。