0

我制作了一个计数器应用程序,当用户在控制台中输入“停止”时,它使用线程来中断计数。我已经仔细检查了我的代码,但看不到问题所在。我是线程新手,所以任何人都可以看看这个。

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.
    }

}
4

1 回答 1

6

您的 while 循环检查“停止”字符串的格式不正确。它应该是这样的:

while(!s.equals("stop"))
{   //Wait for the user to enter stop.
    s=scanner.nextLine();
}
counter.interrupt();  //Interrupt the counter thread.
于 2012-04-30T22:29:08.623 回答