java – 为什么程序没有终止?

我是使用Timer类的新手,因此在将其合并到我的项目之前尝试使用它.我想知道为什么这个程序在计数达到5时不会终止.即使不满足while循环的条件,程序也会继续运行.

package Timer;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;

public class demo {

    private static int count;


    public static void main(String[] args) {
        ActionListener executeThis = new ActionListener(){


            @Override
            public void actionPerformed(ActionEvent arg0) {
                // TODO Auto-generated method stub
                System.out.println("Hello");
                count++;

            }

        };

        Timer timer = new Timer(500, executeThis);
        timer.setInitialDelay(1000);
        timer.start();

        while(count < 5){

        }
    }

}
最佳答案
用于停止计时器

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.atomic.AtomicInteger;


public class Test1 {
    private static AtomicInteger count = new AtomicInteger(0);

    public static void main(String[] args) {
        ActionListener executeThis = new ActionListener(){


            @Override
            public void actionPerformed(ActionEvent arg0) {
                // TODO Auto-generated method stub
                System.out.println("Hello");
                count.getAndIncrement();

            }

        };

        Timer timer = new Timer(500, executeThis);
        timer.setInitialDelay(1000);
        timer.start();

        while(count.get() < 5){

        }
        timer.stop();

    }
}

但我认为这将是正确的方法

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * User: Romeo Sheshi 
 * Date: 21/03/16
 * Time: 12:12
 */
public class Test {
    private static AtomicInteger count = new AtomicInteger(0);
    private static Timer timer;
    public static void main(String[] args) {


        ActionListener executeThis = new ActionListener(){


            @Override
            public void actionPerformed(ActionEvent arg0) {
                // TODO Auto-generated method stub
                System.out.println("Hello");

                if( count.incrementAndGet()==5){
                   stopTimer();
                }

            }

        };
        timer = new Timer(500, executeThis);
        timer.setInitialDelay(1000);
        startTimer();

        while ( count.get()<5){}

    }

    public static void startTimer(){
        timer.start();
    }

    public static void stopTimer(){
        timer.stop();
    }
}

转载注明原文:java – 为什么程序没有终止? - 代码日志