gpt4 book ai didi

java - 计数器应用程序不会停止

转载 作者:行者123 更新时间:2023-12-01 16:34:46 24 4
gpt4 key购买 nike

我制作了一个计数器应用程序,当用户在控制台中输入“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.
}

}

最佳答案

您的 while 循环检查“stop”字符串的格式错误。应该是这样的:

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

关于java - 计数器应用程序不会停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10391339/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com