ユーザーがコンソールに「停止」を入力すると、スレッドを使用してカウントを中断するカウンターアプリケーションを作成しました。コードを再確認しましたが、問題が見つかりません。私はスレッドが初めてなので、誰でもこれを見てください。
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.
}
}