首页 > 代码库 > 如何唤醒Sleep中的线程
如何唤醒Sleep中的线程
主线程调用子线程的interrupt()方法,导致子线程抛出InterruptedException, 在子线程中catch这个Exception,不做任何事即可从Sleep状态唤醒线程,继续执行。 如下测试。
public class SleepThreadTest {
public static void main(String[] args){
Thread myThread = new Thread(new TestThread(1));
myThread.start();
try {
Thread.sleep(3000);
myThread.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static class TestThread implements Runnable{
private int i;
public TestThread(int i){
this.i = i;
}
@Override
public void run() {
while(i<10){
System.out.println(i + " time:" + new Date());
i++;
if(i==4){
try {
Thread.sleep(10000);
} catch (InterruptedException e1) {
System.out.println("interrupt myThread...");
}
}
}
}
}
}
result:
1 time:Mon Jun 16 15:19:56 CST 2014
2 time:Mon Jun 16 15:19:56 CST 2014
3 time:Mon Jun 16 15:19:56 CST 2014
interrupt myThread...
4 time:Mon Jun 16 15:19:59 CST 2014
5 time:Mon Jun 16 15:19:59 CST 2014
6 time:Mon Jun 16 15:19:59 CST 2014
7 time:Mon Jun 16 15:19:59 CST 2014
8 time:Mon Jun 16 15:19:59 CST 2014
9 time:Mon Jun 16 15:19:59 CST 2014