我做了一個計數器應用程序,當用戶在控制檯輸入「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.
}
}
什麼是您的控制檯輸出?你是否收到「Counter Interrupted」消息? –
不,這是我的輸出。注意我試圖用我的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