java计时器将无法正常工作

Ric*_*cco 2 java timer

为什么这不起作用?

我希望它每秒打印一次.

谢谢.

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

public class test2 {

public static void main(String[] args) {

    Timer timer = new Timer(1000, new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            System.out.println("hello");
        }
    });

    timer.start();
    }
}
Run Code Online (Sandbox Code Playgroud)

dav*_*vid 7

您的程序在计时器甚至可以运行一次之前终止.当main方法终止时,程序终止,所有线程也将终止.这包括您的计时器线程.

请尝试以下方法:

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

public class test2 {

    public static void main(String[] args) {

        Timer timer = new Timer(1000, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("hello");
            }
        });

        timer.start();
        }

        while (true) /* no operation */;
    }
}
Run Code Online (Sandbox Code Playgroud)