java定时器停止可以使用timer类的cancel方法,代码如下:
final Timer timer = new Timer(); TimerTask task = new TimerTask() { private int count; @Override public void run() { this .count++; System.out.println(count); if (count == 10 ) { System.out.println( "定时器停止了" ); timer.cancel(); // 停止定时器 } } }; timer.schedule(task, 0 , 1000 ); // 1秒一次 |
运行结果如下:
![](https://i-blog.csdnimg.cn/blog_migrate/02d964d6d3223e8f374f975c0022af17.png)