简体   繁体   English

使用Java线程作为任务sheduler,

[英]Use Java thread as a task sheduler,

i want to schedule task every amount of milliseconds, and i know about Timers, Executors and so on. 我想每隔几毫秒安排任务,我知道计时器,执行器等。 I found that this method is the most accurate. 我发现这种方法最准确。 But i just want to know can my way be too heavy for a (big) program? 但我只想知道我的方式对于(大)程序来说可能太重了吗?

    new Thread(() -> {
        long time = System.currentTimeMillis();
        while (true) {
            if (System.currentTimeMillis() - time >= 1000) {
                // Scheduled task
                System.out.println(new SimpleDateFormat("HH:mm:ss:SSS").format(new Date(System.currentTimeMillis())));
                time = System.currentTimeMillis();
            }
        }
    }).start();

Your method creates a new thread for each repetitive task. 您的方法为每个重复任务创建一个新线程。 Each thread requires allocation of an entire stack. 每个线程都需要分配整个堆栈。 As a result, the memory consumption of your method is a lot bigger than it needs to be. 因此,您的方法的内存消耗比它需要的大很多。 This could become an issue if you create enough of these timer threads. 如果您创建足够的这些计时器线程,这可能会成为一个问题。

You would be better off using a java.util.Timer and TimerTasks if you are going to have a large number of these tasks. 如果要完成大量的这些任务,最好使用java.util.Timer和TimerTasks。

Incidentally, as written, your task timing will drift, because occasionally there will be an extra millisecond or more between the triggering of the task and resetting the time variable. 顺便提一下,正如所写,你的任务时间会漂移,因为在触发任务和重置time变量之间偶尔会有一个额外的毫秒或更time That can be fixed in your code, though. 但是,这可以在您的代码中修复。

Your code has multiple issue. 您的代码有多个问题。

1.Your code is continuously executing though it should wait for the given time if it is not ready.You can use delay queue or other concurrent api available where if item is not ready it may wait or sleep and when item ready it will notify the worker thread. 1.如果代码没有准备好,你的代码会持续执行,但它应该等待给定的时间。你可以使用延迟队列或其他并发api,如果项目没有准备就可以等待或睡觉,当项目准备就绪时它会通知工人线程。

2.It is single threaded if it breaks or one task taking long time then it will escape next schedule.And it is not logically schedule on every 30 sec for an example.It is counting after execution completion from where it is calculating. 2.它是单线程的,如果它中断或一个任务需要很长时间,那么它将逃脱下一个时间表。并且它不是每30秒逻辑安排一个例子。它在计算执行完成后计数。

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

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