我无法阻止线程在Java中运行

时间:2019-05-27 10:32:35

标签: java multithreading

正如标题所述,我似乎无法停止线程的运行。

这是我的两个班级:

class MouseHandler implements MouseListener
{
    private Chronometer chronometer= new Chronometer();

    public void mouseClicked(MouseEvent e) {}
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}
    public void mousePressed(MouseEvent e)
    {
        if(SwingUtilities.isLeftMouseButton(e))
        {
            if(Condition1)
            {
                chronometer.start();
                System.out.println("The Thread is started");
            }
            if(Condition2)
            {
                System.out.println("Stopping the Thread...");
                chronometer.stopRunning();
            }
            if(Condition3)
            {
                System.out.println("Stopping the Thread...");
                chronometer.stopRunning();
            }
        }
    }
    public void mouseReleased(MouseEvent e) {}
}
class Chronometer extends Thread
{
    private volatile boolean flag=true;
    public void stopRunning()
    {
        System.out.println("Method StopRunning entered");
        flag=false;
        System.out.println("Current flag value= " + flag);
    }
    public void run()
    {
        int sec=0;
        while(flag)
        {
            //static method that set the text of a JLabel
            setInitPanel.setChronText(sec);
            try {
                sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            sec++;
            System.out.println("The Thread is running...");
            System.out.println("Current flag value= " + flag);
        }
    }
}

MouseHandler类中的ifs可以正常工作。输出为:

The Thread is started
The Thread is running...
Current flag value= true
//condition2 or condition3 occurs
Stopping the Thread...
Method StopRunning is entered
Current flag value= false
The Thread is running...
Current flag value= true
The Thread is running...
Current flag value= true
The Thread is running...
Current flag value= true
The Thread is running...
Current flag value= true
//and it just keeps going

JLabel实际上是在线程启动时更改文本的。但是它永远不会停止。我还尝试过在ifs中使用interrupt()方法,同时在while中(在run方法内部)使用!isInterrupted()。这也不起作用。我还尝试使Chronometer类实现Runnable的方法相同。它也不起作用。我在做什么错了?

0 个答案:

没有答案