Я сделал приложение-счетчик, в котором оно использует потоки для прерывания счета, когда пользователь вводит "стоп" в консоль. Я дважды проверил свой код, и я не вижу проблемы. Я новичок в темах, так что может кто-нибудь взглянуть на это.
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.
}
}