简体   繁体   English

每秒恒定“滴答声”(每秒线程)Java

[英]Constant “ticks” per second thread Java

I know this may be completely obvious for more experenced programmers but I can't find anything on it. 我知道对于经验丰富的程序员来说,这可能是完全显而易见的,但我找不到任何东西。

I need to make a thread that "ticks" at a constant amount of times per second no matter how long the task it has to execute is. 无论线程必须执行多长时间,我都需要创建一个以每秒固定次数“滴答”的线程。 A task that takes longer than each tick would obviously not be possible and slow the number of ticks per second. 花费比每个刻度更长的任务显然是不可能的,并且会减慢每秒的刻度数。

Thanks. 谢谢。

Use java.util.Timer.scheduleAtFixedRate : 使用java.util.Timer.scheduleAtFixedRate

 public void scheduleAtFixedRate(TimerTask task, Date firstTime, long period) 

Schedules the specified task for repeated fixed-rate execution , beginning at the specified time. 从指定的时间开始计划指定的任务以重复执行固定速率 Subsequent executions take place at approximately regular intervals, separated by the specified period. 随后的执行大约每隔固定的时间间隔执行一次,并间隔指定的时间。

In fixed-rate execution, each execution is scheduled relative to the scheduled execution time of the initial execution. 在固定速率执行中,相对于初始执行的计划执行时间来计划每个执行。 If an execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will occur in rapid succession to "catch up." 如果执行由于某种原因(例如垃圾回收或其他后台活动)而延迟,则将快速连续发生两个或更多执行以“追上”。 In the long run, the frequency of execution will be exactly the reciprocal of the specified period (assuming the system clock underlying Object.wait(long) is accurate). 从长远来看,执行频率将恰好是指定时间段的倒数(假设Object.wait(long)底层的系统时钟是准确的)。 As a consequence of the above, if the scheduled first time is in the past, then any "missed" executions will be scheduled for immediate "catch up" execution. 由于上述原因,如果计划的第一次是过去的时间,那么任何“缺失”的执行都将被安排立即执行“追赶”。

Fixed-rate execution is appropriate for recurring activities that are sensitive to absolute time, such as ringing a chime every hour on the hour, or running scheduled maintenance every day at a particular time. 固定速率执行适用于对绝对时间敏感的重复活动,例如每小时每小时发出一声提示音,或每天在特定时间运行计划的维护。 It is also appropriate for recurring activities where the total time to perform a fixed number of executions is important, such as a countdown timer that ticks once every second for ten seconds. 对于执行固定次数执行的总时间很重要的重复活动,例如倒数计时器,它每秒钟滴答一次十秒钟,这也很适合。 Finally, fixed-rate execution is appropriate for scheduling multiple repeating timer tasks that must remain synchronized with respect to one another. 最后,固定速率执行适用于安排多个重复计时器任务,这些任务必须彼此保持同步。

Here is a Thread version. 这是Thread版本。 A Timer would be the way to go but if you really want to use your own thread. Timer是最好的选择,但是如果您确实想使用自己的线程。

new Thread(new Runnable() {

    @Override
    public void run() {
        try {
        long before, sleepDuration, operationTime;
        for(int i=0;i<100;i++) {
            before = System.currentTimeMillis();
            // do your operations
            operationTime = (long)(1500*Math.random());
            System.out.print("Doing operations for "+operationTime+"ms\t");
            Thread.sleep(operationTime);

            // sleep for up to 1000ms
            sleepDuration = Math.min(1000, Math.max(1000 - (System.currentTimeMillis() - before), 0));
            Thread.sleep(sleepDuration);
            System.out.println("wait\t"+sleepDuration+"ms =\telapsed " + (operationTime+sleepDuration) + (operationTime > 1000 ? "<" : ""));
        }
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}).start();

The Timer and TimerTask classes are perfect for your use. TimerTimerTask类非常适合您使用。

Take a look at the docs http://docs.oracle.com/javase/6/docs/api/index.html?java/util/Timer.html or follow this lesson http://enos.itcollege.ee/~jpoial/docs/tutorial/essential/threads/timer.html 看看docs http://docs.oracle.com/javase/6/docs/api/index.html?java/util/Timer.html或遵循本课程http://enos.itcollege.ee/~ jpoial /文档/教程/本质/线程/ timer.html

Let me know if I misunderstood your question. 如果我误解了您的问题,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM