[JavaEE]如何唤醒Sleep中的线程

[an error occurred while processing the directive]

主线程调用子线程的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 20142 time:Mon Jun 16 15:19:56 CST 20143 time:Mon Jun 16 15:19:56 CST 2014interrupt myThread...4 time:Mon Jun 16 15:19:59 CST 20145 time:Mon Jun 16 15:19:59 CST 20146 time:Mon Jun 16 15:19:59 CST 20147 time:Mon Jun 16 15:19:59 CST 20148 time:Mon Jun 16 15:19:59 CST 20149 time:Mon Jun 16 15:19:59 CST 2014

[an error occurred while processing the directive]
Copyright © 2088 米策网游动态中心-新游测试与公会争霸 All Rights Reserved.
友情链接