Pen*_*826 0 java multithreading interrupt
我做了一个计数器应用程序,当用户在控制台中输入"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.
}
}
Run Code Online (Sandbox Code Playgroud)
小智 6
你的while循环检查'stop'字符串是不正确的.它应该是这样的:
while(!s.equals("stop"))
{ //Wait for the user to enter stop.
s=scanner.nextLine();
}
counter.interrupt(); //Interrupt the counter thread.
Run Code Online (Sandbox Code Playgroud)