Thread.sleep()挂了吗? [英] Thread.sleep() is hung?

查看:157
本文介绍了Thread.sleep()挂了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我每秒循环的简单代码(不一定是确切的)并在必要时开始工作:

Here's my simple code to loop every second (doesn't need to be exact) and kick off a job if necessary:

while (true) {
  // check db for new jobs and 
  // kick off thread if necessary
  try {
    Thread.sleep(1000);
  } catch(Throwable t) {
    LOG.error("", t);
  }
}

这段代码已经好几个月了。 就在昨天,我们开始遇到问题,其中一个服务器似乎挂在Thread.sleep(1000)方法中。 IOW - 已经过了一天而且Thread.sleep还没有返回。我启动了jconsole并获取有关该线程的信息。

This code has worked fine for several months. Just yesterday we started having problems where one of our servers seems to be hung in the Thread.sleep(1000) method. IOW - it's been over a day and the Thread.sleep hasn't returned. I started up jconsole and get this info about the thread.

Name: Thread-3
State: TIMED_WAITING
Total blocked: 2  Total waited: 2,820

Stack trace: 
 java.lang.Thread.sleep(Native Method)
xc.mst.scheduling.Scheduler.run(Scheduler.java:400)
java.lang.Thread.run(Thread.java:662)

Scheduler.java:400是上面的Thread.sleep行。按照我的预期,jconsole输出不会每秒增加Total wait。事实上,它根本没有变化。我甚至关闭了jconsole并重新启动它,希望可能会强制刷新,但只会再次获得相同的数字。我不知道除了jvm错误地挂在sleep命令上之外还有什么其他的解释。然而,在我这些年里,我对jvm的问题很少,我认为这一定是我的疏忽。

Scheduler.java:400 is the Thread.sleep line above. The jconsole output doesn't increment "Total waited" every second as I'd expect. In fact it doesn't change at all. I even shut down jconsole and started it back up in the hopes that maybe that would force a refresh, but only got the same numbers again. I don't know what other explanation there could be besides that the jvm has incorrectly hung on the sleep command. In my years, though, I've had so few problems with the jvm that I assume it must be an oversight on my part.

注意:其他需要注意的是没有其他线程处于活动状态。 IOW - cpu几乎处于空闲状态。我读到某个地方,如果另一个线程处于活动状态,Thread.sleep可能会被合法地饿死,但这不是这种情况。

note: The other thing to note is that no other thread is active. IOW - the cpu is nearly idle. I read somewhere that Thread.sleep could be legitimately starved if another thread was active, but that isn't the case here.

solaris版本:

solaris version:

$ uname -a
SunOS xcmst 5.10 Generic_141415-08 i86pc i386 i86pc

java版本:

$ java -version
java version "1.6.0_26"
Java(TM) SE Runtime Environment (build 1.6.0_26-b03)
Java HotSpot(TM) Server VM (build 20.1-b02, mixed mode)


推荐答案

除了bdonlan提到的你可能想要研究的内容 ScheduledThreadPoolExecutor 。我在一个非常类似的项目上工作,这个对象使我的生活更轻松,这要归功于这个小片段。

In addition to what bdonlan mentioned you may want to look into ScheduledThreadPoolExecutor. I work on a very similar type of project and this object has made my life easier, thanks to this little snippet.


如果执行此任务的时间超过其周期,则
后续执行可能会延迟,但不会同时执行

If any execution of this task takes longer than its period, then subsequent executions may start late, but will not concurrently execute.

我希望这有帮助!

这篇关于Thread.sleep()挂了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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