空的 while 循环被视为不良实践吗?

huangapple go评论82阅读模式
英文:

Is an empty while loop considered bad practice?

问题

我将从服务器下载数据,如果下载失败,最多尝试3次。

public class DownloadFile {

    private boolean isSuccessful;

    public DownloadFile() {
        int attempt = 0;

        while(!isSuccessful && (attempt++ < 3)) {
            DownloadFileThread.start();
            while (DownloadFileThread.isAlive());
        }
    }

    private Thread DownloadFileThread = new Thread() {
        public void run() {
            try {
                // 从服务器下载文件

                isSuccessful = true;
            } catch (Exception e) {
                isSuccessful = false;
            }
        }
    }

}

如您在上面的示例中所见,我在第10行(实际上是第11行)处有一个空的 while 循环,以确保在再次检查 while 循环条件之前,为 isSuccessful 赋值,根据 DownloadFileThread 的结果。

这样做被认为是不良实践吗?是否存在更好的方法或者正确的方式来实现这个功能?

尽管上述代码能够产生有效结果,但我对自己编写的代码并不感到满意...

英文:

I am to download data from the server, with a maximum of 3 attempts if the download fails.

public class DownloadFile {

    private boolean isSuccessful;

    public DownloadFile() {
        int attempt = 0;

        while(!isSuccessful &amp;&amp; (attempt++ &lt; 3)) {
            DownloadFileThread.start();
            while (DownloadFileThread.isAlive());
        }
    }

    private Thread DownloadFileThread = new Thread() {
        public void run() {
            try {
                // download file from server

                isSuccessful = true;
            } catch (Exception e) {
                isSuccessful = false;
            }
        }
    }

}

As you can see in the above example, I have an empty while loop in (what would be) line 10 to force guarantee isSuccessful is assignment a value based on the outcome of the DownloadFileThread before checking the condition in the while loop again.

Is it considered bad practice to do such a thing? Is there better approach or a correct way to do this?

While the above code does produce a valid result, I am not exactly proud of the code I have written...

答案1

得分: 3

在这种情况下,这是一种不好的做法,因为Java提供了更好的机制来等待线程完成:Thread.join(),或者考虑使用更现代的特性,比如CompletableFuture,或者允许你等待任务完成的ExecutorService

使用空循环进行等待会不必要地消耗大量的CPU资源,这可能意味着系统中的其他任务执行速度会比本应更慢。

英文:

Yes, in this case it is a bad practice, because Java offers better mechanisms to wait for completion of a thread: Thread.join(), or consider using more modern features like CompletableFuture or an ExecutorService that allows you to wait for a task to complete.

Using an empty loop to wait will consume a lot of CPU power unnecessarily, which might mean other tasks on your system will perform slower than they could otherwise.

答案2

得分: 1

不一定,但在这种情况下,这是一种繁忙等待的做法,尤其在多线程程序中不推荐。它会使CPU保持繁忙,在你的情况下会干扰DownloadFileThread。

英文:

Not necessarily, but in this case this is a busy wait which is bad practice especially in multi-threaded programs. It keeps the CPU busy and in your case interferes with DownloadFileThread.

答案3

得分: 1

在你的情况下,while循环将永久执行,从其他事物中夺取处理时间,可能还会从下载线程中夺取处理时间。如果你只是想等待下载完成,为什么不使用Thread.join()呢?它是阻塞的,意味着在DownloadThread完成之前,你将无法在主线程中执行任何操作,但在这种情况下,你的while循环也会这样做,并且会占用更多的系统资源。

英文:

In your case the while loop will execute permanently stealing process time from other things, maybe also from your download thread.
If you simply want to wait until your download is done, why don´t you use Thread.join() ?
It´s blocking, meaning that you won´t be able to execute anything in your main-thread until the DownloadThread is done but your while loop does this as well in this case and use more system resources on top.

huangapple
  • 本文由 发表于 2020年5月5日 01:59:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/61598657.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定