在Java中使用while循环是否不安全? [英] Is using while loop in Java unsafe?

查看:88
本文介绍了在Java中使用while循环是否不安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说Java循环需要最大的CPU能力才能尽快运行.

I heard that loops in Java take maximum CPU power to run as fast as possible.

使用长时间运行的while循环是否不安全?

Is it unsafe to use while loops that run for a long time?

我知道,如果我将线程休眠一小会儿,那么在线程中是安全的.

I know that it is safe in threads if I sleep the thread for a little time.

但是不是在睡眠线程安全的内部的快速持久循环吗?

But are fast long-lasting loops that are not inside a sleeping thread-safe?

推荐答案

软件

不,不是这样.只要您不会因保持锁引起的问题而使代码的其他部分死锁,并且您具有有效的停止条件,从而使用户不需要终止您的应用程序,那么您就可以了. 但是 ,如果您正在创建新对象并保留对它们的引用,则可能会耗尽内存.

Software

No, not really. As long as you don't cause issues with held locks deadlocking other parts of code and you have valid stopping conditions so the user doesn't need to kill your application you should be fine. However, if you are creating new objects and hold references to them you could run out of memory.

许多程序(包括Java)在CPU使用率和循环方面都有其应有的份额.游戏,其他编译器,甚至办公应用程序都可以做到这一点.实际上,许多程序都依赖于无限循环(尽管有停止条件,但它们可以是 while(true)类型.可以产生热量,但无需担心.

Many programs, including Java, have their fair share of CPU use and loops. Games, other compilers, and even office applications can do this. In fact, many programs rely on infinite loops(albeit with a stopping condition but they can be of the while(true) type. Heat can be generated but it's nothing to worry about.

这篇关于在Java中使用while循环是否不安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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