在什么情况下,while可以比while更有效率? [英] In what situations can do-while be more efficient than while?
问题描述
vs。与do-while
在功能块为空时,同时与do-while在功能上等效 >,尽管看起来更自然:
While and do-while are functionally equivalent when the blocks are empty, although while seems more natural:
do {} while (keepLooping());
while (keepLooping()) {}
一个典型的while / do用例-同时使用空块是用compareAndSet(CAS)强制更新原子对象。例如,下面的代码将以线程安全的方式递增 a
:
One typical use case of a while/do-while with an empty block is to force an update of atomic objects with a compareAndSet (CAS). For example the code below will increment a
in a thread-safe way:
int i;
AtomicInteger a = new AtomicInteger();
while (!a.compareAndSet(i = a.get(), i + 1)) {}
上下文
java.util.concurrent的多个部分使用 do {}而(。 ..)
成语,用于CAS操作和 ForkJoinPool
的javadoc说明:
Several parts of java.util.concurrent use the do {} while (...)
idiom for CAS operations and the javadoc of ForkJoinPool
explains:
有几次发生不寻常的
do {}而(!cas ...)
是强制更新CAS的最简单方法ed变量。
There are several occurrences of the unusual
do {} while (!cas...)
which is the simplest way to force an update of a CAS'ed variable.
因为他们承认这很不正常,所以我认为它们的意思是 best 而不是最简单的。
Since they admit it is unusual, I suppose they meant best rather than simplest.
问题
在某些情况下做{} while(!cas)
比 while(!cas){}
更有效,原因何在? / p>
Are there situations where do {} while (!cas)
can be more efficient than while (!cas) {}
and for what reasons?
推荐答案
所以'do while'意味着它将在while循环中运行一次代码。然后,如果条件为真,则仅在while循环内运行代码。
So a 'do while' means it will run the code in the while loop once. Then, it only runs the code inside the while loop if the condition is true.
简单演示
boolean condition = false;
do{
System.out.Println("this text displayed");
}while(condition == true);
输出显示的文字
正常
while(condition == true){
System.out.Println("this text displayed");
}
输出
- *由于条件为假,因此不显示任何输出。
为什么或在何处使用do ,我没有满足您的需要,所以我无法为您提供帮助。只是确定问题/需求并使用您所知道的知识来解决问题,就像乐高玩具一样,机械式的不是障碍。
Why or where you would use do while, I havn't come accross the need to so I can't help you there. It's just a matter of identifying a problem/need, and using what you know to solve it.similar to lego-the mechanical kind not 'blocks'.
这篇关于在什么情况下,while可以比while更有效率?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!