在java中,如何使线程在特定时间内休眠?
我有一个场景,我想要一个线程在特定的时间内睡眠 代码: 现在,我如何处理在睡眠完成之前,我试图运行的线程被中断的异常击中的情况?线程在被中断后是否会唤醒并进入可运行状态,或者只有在进入可运行状态后,流才会进入catch块在java中,如何使线程在特定时间内休眠?,java,multithreading,sleep,Java,Multithreading,Sleep,我有一个场景,我想要一个线程在特定的时间内睡眠 代码: 现在,我如何处理在睡眠完成之前,我试图运行的线程被中断的异常击中的情况?线程在被中断后是否会唤醒并进入可运行状态,或者只有在进入可运行状态后,流才会进入catch块 根据我的经验,使用睡眠通常是为了补偿程序中其他地方的不好时机,请重新考虑 试试这个: public void run(){ try{ //do something long before = System.curr
public void run(){
try{
//do something
long before = System.currentTimeMillis();
Thread.sleep(3000);
//do something after waking up
}catch(InterruptedException e){
long diff = System.currentTimeMillis()-before;
//this is approximation! exception handlers take time too....
if(diff < 3000)
//do something else, maybe go back to sleep.
// interrupted exception hit before the sleep time is completed.so how do i make my thread sleep for exactly 3 seconds?
}
}
public void run(){
试一试{
//做点什么
很久以前=System.currentTimeMillis();
睡眠(3000);
//醒来后做点什么
}捕捉(中断异常e){
long diff=System.currentTimeMillis()-之前;
//这是近似值!异常处理程序也需要时间。。。。
如果(差值<3000)
//做点别的,也许回去睡觉。
//在睡眠时间完成之前,中断的异常命中。那么,如何使线程睡眠3秒?
}
}
public class ThreadThing implements Runnable {
public void run() {
boolean sawException = false;
for (int i = 0; i < 10; i++) {
try {
//do something
Thread.sleep(300);
//do something after waking up
} catch (InterruptedException e) {
// We lose some up to 300 ms of sleep each time this
// happens... This can be tuned by making more iterations
// of lesser duration. Or adding 150 ms back to a 'sleep
// pool' etc. There are many ways to approximate 3 seconds.
sawException = true;
}
}
if (sawException) Thread.currentThread().interrupt();
}
}
public类ThreadThing实现可运行{
公开募捐{
布尔异常=假;
对于(int i=0;i<10;i++){
试一试{
//做点什么
睡眠(300);
//醒来后做点什么
}捕捉(中断异常e){
//我们每次都会失去300毫秒的睡眠
//发生…这可以通过进行更多的迭代来调整
//持续时间较短。或者在“睡眠”中增加150毫秒
//游泳池等。有很多方法可以使你的时间接近3秒。
sawException=true;
}
}
if(sawException)Thread.currentThread().interrupt();
}
}
你为什么要睡3秒钟?如果只是在一段时间后执行某些操作,请尝试使用。当线程被中断击中时,它将进入中断异常
捕获块。然后,您可以检查线程睡眠的时间,并计算出还有多少睡眠时间。最后,与其吞咽异常,还不如恢复中断状态,以便调用堆栈上层的代码能够处理它
public void run(){
//do something
//sleep for 3000ms (approx)
long timeToSleep = 3000;
long start, end, slept;
boolean interrupted;
while(timeToSleep > 0){
start=System.currentTimeMillis();
try{
Thread.sleep(timeToSleep);
break;
}
catch(InterruptedException e){
//work out how much more time to sleep for
end=System.currentTimeMillis();
slept=end-start;
timeToSleep-=slept;
interrupted=true
}
}
if(interrupted){
//restore interruption before exit
Thread.currentThread().interrupt();
}
}
我这样使用它:
因此,没有必要等待特定的时间结束
public void run(){
try {
//do something
try{Thread.sleep(3000);}catch(Exception e){}
//do something
}catch(Exception e){}
}
中断可能来自外部事件,例如来自操作系统的“正常关机”请求。@Tony:这是相同的原理。中断仍然表示有人故意请求取消线程,而不是像OP的措辞所暗示的那样,线程被“击中”的某种偶然事件。计时器会更好,但它确实引入了竞争和并发问题的可能性,这可以通过睡眠来避免。然而,我认为使用计时器是值得学习的。上面的计时器链接似乎被破坏了
public void run(){
try {
//do something
try{Thread.sleep(3000);}catch(Exception e){}
//do something
}catch(Exception e){}
}