这会暂停我的Java线程一分钟吗? [英] Will this pause my Java thread for a minute?

查看:741
本文介绍了这会暂停我的Java线程一分钟吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里做的东西真的很蠢吗?我试图每分钟左右执行一个方法,永远,或直到我停止程序。

  while(true){ 
this.doSomethingPeriodically();
Calendar now = Calendar.getInstance();
int minutes = now.get(Calendar.MINUTE);
int resume = minutes + 1;
while(now.get(Calendar.MINUTE)< resume){
//等待一分钟
}
}


解决方案

这段代码永远不会离开循环。这是一个无限循环,因为日历实例由现在指向不会改变。



此外,您尝试在此处执行的是实施忙等待<这是一个非常糟糕的主意(它使用CPU时间没有什么有趣的)。



正确的睡眠方式是使用 Thread。 / code> sleep()


Am I doing something really stupid here? I am trying to execute a method every minute or so, forever, or until I stop the program.

	while(true) {
		this.doSomethingPeriodically();
		Calendar now = Calendar.getInstance();
		int minutes = now.get(Calendar.MINUTE);
		int resume = minutes + 1;
		while (now.get(Calendar.MINUTE) < resume) {
			// waiting for a minute
		}
	}

解决方案

This code will never leave the loop. It's an endless loop, since the Calendar instance refered to by now won't change.

Also, what you try to do here is implement busy waiting which is a very bad idea (it uses CPU time doing nothing interesting).

The correct way to sleep is to use Thread.sleep().

这篇关于这会暂停我的Java线程一分钟吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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