你能控制java线程的延迟吗?

发布于 2024-10-22 02:38:48 字数 138 浏览 4 评论 0原文

我正在创建一个小型服务器,它将始终侦听新连接。服务器每秒大约 30 次“醒来”并向客户端发送更新请求。客户端将处于睡眠状态,直到醒来(由最后一个连接建立)并接受请求并启动更新为止。由于交换窗口始终很小,因此如何管理睡眠线程的延迟以获得更准确和精确的睡眠周期测量?

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. 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

自我难过 2024-10-29 02:38:48

不,你不能。

这里有两个完全不同的活动耦合在一起。
一个负责定期唤醒,另一个负责更新客户端。
如果唤醒任务等待更新任务完成,那么其准确性将会受到影响。

您可以做的就是通过在服务器中引入某种程度的异步来解决问题。

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 :)
    );

No you can't.

What you have here is 2 absolutely different activities coupled together.
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 :)
    );
恋竹姑娘 2024-10-29 02:38:48

为什么不能一直保持清醒呢? 观察者/可观察模式对您有任何帮助吗?

Why can't it stay awake throughout? Does the Observer / Observable pattern help you in any way?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文