java中的sleep和join之间的相似性 [英] Similarity between sleep and join in java

查看:121
本文介绍了java中的sleep和join之间的相似性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如问题所示,我想知道线程上sleep和join方法之间的相似性。我已经经历了许多描述睡眠和连接方法之间差异的问题。但我想知道睡眠和连接方法可以互换使用的不同场景。根据我的想法,下面的代码应该以同样的方式工作。我有一个主线程,我在其中启动一个新线程(只有1),我希望主线程等待新线程完成一段时间。代码如下:

As the question suggests , I want to know the similarity between the sleep and join methods on the thread. I have gone through many questions that describe the difference between the sleep and join method. But I would like to know different scenarios where the sleep and join methods could be used interchangeably . According to my thinking following code should work just in the same way. I have a main thread in which I start a new thread (just 1) and I want the main thread to wait for the new thread to complete for some amount of time. The code is as follows:

   newThread.join(10000)

OR,

  Thread.sleep(10000)

但是,当我运行此代码时,我没有得到预期的结果。为什么会这样?技术上它应该是一样的吗?

but , when I run this code I don't get expected results. why is this so? technically it should be the same right?

推荐答案

我不清楚你的实际问题是什么,但你的第三句话说,我想知道睡眠和连接方法可以互换使用的不同场景。

It's not clear to me what your actual question is, but your third sentence in says, "I would like to know different scenarios where the sleep and join methods could be used interchangeably."

从实际角度来看,如果你和一个团队合作软件开发人员编写生产代码时,会有 no 场景,其他开发人员会允许你使用join(long)作为sleep(long)的替代方案。没有办法,没有办法!在某些情况下它实际上会起作用并不重要。

From a practical point of view, if you worked with a team of software developers writing production code, there would be no scenarios in which other developers would permit you to use join(long) as an alternative to sleep(long). No way, no how! It does not matter that there are circumstances under which it would actually work.

生产代码应该是可读的。代码的意图对其他人来说应该是显而易见的。它应该遵循最小惊喜原则(参见清洁代码:Robert C. Martin的敏捷软件工艺手册)。这意味着,当你写foobar.join(n)时,你应该期待foobar线程死掉。您可能已准备好处理超时情况,但这应该是例外,而不是规则。没有其他合理的理由可以调用join(n)。其他任何东西都是黑客,我们不会在生产代码中加入黑客。

Production code should be readable. The intent of the code should be obvious to others. It should obey The Principle of Least Surprise (See Clean Code: A Handbook of Agile Software Craftsmanship by Robert C. Martin). That means, when you write foobar.join(n), you should be expecting the foobar thread to die. You might be prepared to handle the timeout case, but that should be the exception, not the rule. There is no other legitimate reason to call join(n). Anything else would be a "hack", and we do not put hacks in production code.

这篇关于java中的sleep和join之间的相似性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆