Java中的时间间隔

编程入门 行业动态 更新时间:2024-10-24 20:17:04
本文介绍了Java中的时间间隔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何在一段时间后调用一个方法? 例如,如果想在2秒后在屏幕上打印一个声明,它的程序是什么?

how to call a method after a time interval? e.g if want to print a statement on screen after 2 second, what is its procedure?

System.out.println("Printing statement after every 2 seconds");

推荐答案

答案是使用javax.swing.Timer和java.util.Timer在一起:

The answer is using the javax.swing.Timer and java.util.Timer together:

private static javax.swing.Timer t; public static void main(String[] args) { t = null; t = new Timer(2000,new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.out.println("Printing statement after every 2 seconds"); //t.stop(); // if you want only one print uncomment this line } }); java.util.Timer tt = new java.util.Timer(false); tt.schedule(new TimerTask() { @Override public void run() { t.start(); } }, 0); }

显然,使用java可以达到2秒的打印间隔。仅限util.Timer,但是如果你想在一次打印后停止它,那么就会很难。

Obviously you can achieve the printing intervals of 2 seconds with the use of java.util.Timer only, but if you want to stop it after one printing it would be difficult somehow.

同样不要在你的代码中混合使用线程而不用线程!

Also do not mix threads in your code while you can do it without threads!

希望这会有所帮助!

更多推荐

Java中的时间间隔

本文发布于:2023-10-23 22:59:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1522251.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:间隔   时间   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!