简体   繁体   English

您可以控制Java线程的延迟吗?

[英]Can you control the latency for java threads?

I'm creating a tiny server that will always listen for new connections. 我正在创建一个微型服务器,该服务器将始终侦听新连接。 About 30 times a second the server will "wake up" and send an update request to a client. 服务器将每秒大约30次“唤醒”并向客户端发送更新请求。 The client will be asleep until it's time to wake up (as established by the last connection) and accept the request and fire off the update. 客户端将一直处于睡眠状态,直到该被唤醒(由上一个连接建立)并接受请求并启动更新。 Because the window for the exchange is going to consistently be small, how do I manage the latency of the sleep thread to get a more accurate and precise measurement of sleep cycles? 因为交换的窗口将一直很小,所以我该如何管理睡眠线程的延迟以更准确地测量睡眠周期?

No you can't. 不,你不能。

What you have here is 2 absolutely different activities coupled together. 您在这里拥有的是2个绝对不同的活动,它们相互耦合。 One is responsible for periodical wakeups and the other takes care of updating the client. 一个负责定期唤醒,另一个负责更新客户端。 If the wakeup task waits for update task to be done then its accuracy will suffer. 如果唤醒任务等待更新任务完成,则其准确性将受到影响。

What you can do is solve the problem by introducing some degree of asynchrony into your server. 您可以做的是通过在服务器中引入某种程度的异步来解决问题。

ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

    final Runnable notificationTask = new Runnable() {
        @Override public void run() {
            updater.sendUpdate();                          // just *notify* the updater to do an update
        }
    };

    executor.scheduleAtFixedRate(
        notificationTask, 0, 33333333, TimeUnit.NANOSECONDS // freakishly accurate :)
    );

Why can't it stay awake throughout? 为什么它不能一直保持清醒? Does the Observer / Observable pattern help you in any way? 观察者/可观察模式是否对您有任何帮助?

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

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