2012-04-30 39 views
0

我做了一個計數器應用程序,當用戶在控制檯輸入「stop」時,它使用線程中斷計數。我已經加倍檢查了我的代碼,並且看不到問題。我是新來的線程,所以任何人都可以看看這個。計數器應用程序不停止

import java.util.Scanner; 

public class CounterInterruptApp 
{ 

    public static void main(String[] args) 
    { 
     new CounterInterruptApp().start(); 
    } 

    public void start() 
    { 
     Thread counter = new Counter(); //Instantiate the counter thread. 
     counter.start(); //Start the counter thread. 

     Scanner scanner = new Scanner(System.in); 
     String s = ""; 
     while(!s.equals("stop")); //Wait for the user to enter stop. 
     s=scanner.next(); 
     counter.interrupt(); //Interrupt the counter thread. 
    } 

} 



public class Counter extends Thread //Extend Thread for the use of the Thread Interface. 
{ 
    public void run()//Run method. This is part of the Thread interface. 
    { 
     int count = 0; 
     while(!isInterrupted()) 
     { 
      System.out.println(this.getName() + "Count: " + count); 
      count++; 
      try //Try/Catch statement. 
      { 
       Thread.sleep(1000); //Make the Thread sleep for one second. 
      } catch(InterruptedException e) { 
       break; 
      } 
     } 
     System.out.println("Counter Interrupted."); //Display the message Counter Interrupted. 
    } 

} 
+0

什麼是您的控制檯輸出?你是否收到「Counter Interrupted」消息? –

+0

不,這是我的輸出。注意我試圖用我的while((!s.equals(「stop」))指定程序來停止程序。Thread-0Count:0 Thread-0Count:1 Thread-0Count:2 Thread-0Count:3 stopThread-0Count:4 線程0Count:5 停止 線程0Count:6 停止 線程0Count:7 停止 線程0Count:8 停止 線程0Count:9 線程0Count:10 Thread-0Count:11 Thread-0Count:12 Thread-0Count:13 Thread-0Count:14 Thread-0Count:1 5 – Pendo826

回答

6

您的while循環檢查'停止'字符串是不合格的。 它應該是這樣的:

while(!s.equals("stop")) 
{ //Wait for the user to enter stop. 
    s=scanner.nextLine(); 
} 
counter.interrupt(); //Interrupt the counter thread. 
+0

即使使用花括號,控制檯中的停止也無法中斷程序。 – Pendo826

+2

@ConorPendlebury在這段時間後刪除分號 –

+0

它應該工作..鍵入'你好'後你是否按了回車鍵?請注意信箱。 –