小编Der*_*rek的帖子

如何避免使用Thread.Sleep

在我下载最新版本的Netbeans之前,我从未想过使用Thread.Sleep.Netbeans现在警告你不要使用Thread.Sleep.所以我做了一些关于这个主题的研究,发现人们说你只需要使用Thread.Sleep进行调试/测试,如果你在任何时候使用它,那么你的代码编写得很糟糕.

所以我的问题是如何在以下情况下不使用Thread.Sleep.

我编写了一个与其他应用程序连接的服务器应用程序.服务器有两个线程:

  1. 处理来自套接字的数据并发回其他信息或仅发送简单的知识.

  2. 这是主线程.在开始套接字线程后,它将进入无限循环.在这个while循环中,我检查以确保套接字线程仍处于活动状态,并且用户没有要求通过TrayIcon接口退出应用程序.然后我睡觉并继续循环.

使用此应用程序,TrayIcon是唯一的UI.

这是我引用的片段:

// continues running as long as the exitth file is not present and 
// the tray icon is not in a safe to exit status.

while(doNotExit())
{

    if (getPrimaryThread() == null || !getPrimaryThread().isAlive())
        resetsThreadAndSocket();

    try
    {
        // check to see if the socket threads are still active, if not create new ones.
        if ((getPrimaryThread() == null || !getPrimaryThread().isAlive()))       
            createSocketThread();

        // check right before sleeping that the user does not want to exit.
        if(getTrayIcon().isExiting()) …
Run Code Online (Sandbox Code Playgroud)

java multithreading sleep

9
推荐指数
2
解决办法
3912
查看次数

标签 统计

java ×1

multithreading ×1

sleep ×1