最近我一直在使用大数字循环打印出来Hello World
:
int counter = 0;
while(true) {
//loop for ~5 seconds
for(int i = 0; i < 2147483647 ; i++) {
//another loop because it's 2012 and PCs have gotten considerably faster :)
for(int j = 0; j < 2147483647 ; j++){ ... }
}
System.out.println(counter + ". Hello World!");
counter++;
}
Run Code Online (Sandbox Code Playgroud)
我知道这是一个非常愚蠢的方法,但我还没有在Java中使用任何计时器库.怎么会修改上面打印每说3秒?
Tim*_*der 184
如果要执行定期任务,请使用ScheduledExecutorService
.特别是ScheduledExecutorService.scheduleAtFixedRate
代码:
Runnable helloRunnable = new Runnable() {
public void run() {
System.out.println("Hello world");
}
};
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(helloRunnable, 0, 3, TimeUnit.SECONDS);
Run Code Online (Sandbox Code Playgroud)
Roh*_*ain 178
您还可以查看可用于安排任务每秒运行的类Timer
和TimerTask
类n
.
您需要一个扩展TimerTask
和覆盖该public void run()
方法的类,每次将该类的实例传递给timer.schedule()
方法时都会执行该类.
这是一个例子,Hello World
每5秒打印一次: -
class SayHello extends TimerTask {
public void run() {
System.out.println("Hello World!");
}
}
// And From your main() method or any other method
Timer timer = new Timer();
timer.schedule(new SayHello(), 0, 5000);
Run Code Online (Sandbox Code Playgroud)
小智 34
试着这样做:
Timer t = new Timer();
t.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("Hello World");
}
}, 0, 5000);
Run Code Online (Sandbox Code Playgroud)
此代码将每隔5000毫秒(5秒)运行打印到控制台Hello World.有关详细信息,请阅读https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Timer.html
tmw*_*nik 14
我用计时器搞清楚了,希望它有所帮助.我从使用的计时器java.util.Timer
和TimerTask
来自同一个包.见下文:
TimerTask task = new TimerTask() {
@Override
public void run() {
System.out.println("Hello World");
}
};
Timer timer = new Timer();
timer.schedule(task, new Date(), 3000);
Run Code Online (Sandbox Code Playgroud)
最简单的方法是将主线程设置为休眠 3000 毫秒(3 秒):
for(int i = 0; i< 10; i++) {
try {
//sending the actual Thread of execution to sleep X milliseconds
Thread.sleep(3000);
} catch(InterruptedException ie) {}
System.out.println("Hello world!");
}
Run Code Online (Sandbox Code Playgroud)
这将使线程停止至少 X 毫秒。线程可能会休眠更多时间,但这取决于 JVM。唯一能保证的是线程将至少休眠那些毫秒。看看文档Thread#sleep
:
使当前正在执行的线程休眠(暂时停止执行)指定的毫秒数,具体取决于系统计时器和调度程序的精度和准确性。
public class HelloWorld extends TimerTask{
public void run() {
System.out.println("Hello World");
}
}
public class PrintHelloWorld {
public static void main(String[] args) {
Timer timer = new Timer();
timer.schedule(new HelloWorld(), 0, 5000);
while (true) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
System.out.println("InterruptedException Exception" + e.getMessage());
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
创建无限循环,配置了广告调度程序任务。
归档时间: |
|
查看次数: |
225638 次 |
最近记录: |