Home > Back-end >  Blocking threads
Blocking threads

Time:09-27

Thread class provides static methods sleep () to run the method of Thread block specified milliseconds,
Note: need to capture the blocking abnormal interruption here! How to understand, is to wake up during sleep is not nature to wake, wake by external forces,

New Thread (() - & gt; {
Try {
//thread block 2 seconds,
Thread.sleep(2000);
//2 seconds after perform print
System. Out.println (" I'm free!" );
{} catch InterruptedException (e)
e.printStackTrace();
}
}).start();
Method must be wake up with sleep ah, also is the interrupt thread block, through the thread instance call interrupt method (will trigger the exception), I write here convenience anonymous classes, can't call don't call, forget it, stick to glance at the code,

Thread the t1=new Thread (() - & gt; {
Try {
Thread.sleep(5000);
{} catch InterruptedException (e)
e.printStackTrace();
}
});
T1. Start ();

New Thread (() - & gt; {
System. Out.println (" I want to interrupt the t1 thread to sleep!" );
T1 interrupt ();
}).start();

Results:
I want to interrupt the t1 thread to sleep!
Java. Lang. InterruptedException: sleep interrupted

CodePudding user response:

Sleep sleep, under normal circumstances can sleep to nature to wake, then work,
Interrupt is a kind of forced to interrupt a thread, it is not just wake up, but also destroy the whole thread running,

For example: you work tired, set the alarm ten minutes of sleep, wake up to continue working,
If you sleep in 5 minutes, when suddenly there is a fire, it's not just wake up, also won't continue to work,
  • Related