public class Hi { public static void main(String args[]) throws java.io.IOException { TimerTask task = new TimerTask() { public void run() { System.out.println("Hi"); } }; Timer timer = new Timer(); timer.schedule(task, 0, 500); System.out.println("Press ENTER to stop"); System.in.read(new byte[10]); timer.cancel(); } } Java Runtime Environment工作的方式是只要有一个线程在运行,程序就不退出。这样,当取消被调用,没有其它线程在运行了,则程序退出。有一些系统线程在运行,如碎片收集程序。这些系统线程也被称为后台线程。后台线程的存在不影响运行环境被关闭,只有非后台线程保证运行环境不被关闭。