diff options
Diffstat (limited to 'src/old/interruptThread/model/SimpleModel2.java')
| -rw-r--r-- | src/old/interruptThread/model/SimpleModel2.java | 63 |
1 files changed, 63 insertions, 0 deletions
diff --git a/src/old/interruptThread/model/SimpleModel2.java b/src/old/interruptThread/model/SimpleModel2.java new file mode 100644 index 0000000..73aa3d0 --- /dev/null +++ b/src/old/interruptThread/model/SimpleModel2.java @@ -0,0 +1,63 @@ +package old.interruptThread.model; + +/** + * 线程关闭模型2 + * 宗旨:外部线程通知该线程中断,该线程自行业务结束 + * 存在阻塞的循环业务操作,如Thread.sleep(),Thread.wait(),Thread.join() 等 + * 外部线程执行thread.interrupt();该线程会抛出异常InterruptedException + * 即 须要增加对该异常的捕捉处理 + * + * @date Feb 21, 2013 10:30:53 AM + * @author ZhangGang + * + */ +public class SimpleModel2 implements Runnable{ +volatile boolean stop = false; + +public static void main(String[] args) throws Exception { + Thread thread = new Thread(new SimpleModel2(), "My Thread2"); + System.out.println("Starting thread..."); + thread.start(); + Thread.sleep(4000); + System.out.println("Interrupting thread..."); + thread.interrupt(); //等同于 future.cancel(true) ; + System.out.println("线程是否中断:" + thread.isInterrupted()); + Thread.sleep(3000); + System.out.println("Stopping application..."); +} + +public void run() { + while (!stop && true) { + + /* 模拟睡眠1秒操作 替换为完整的业务 */ + long time = System.currentTimeMillis(); + while ((System.currentTimeMillis() - time < 1000)) { + } + + /** + * Thread.currentThread().isInterrupted() 为获取线程中断状态,获取后不改变状态值 + * ps:catch(InterruptedException e)异常捕获 上面的取值会改变为false + */ + System.out.println("My Thread is running... isInterrupted? "+Thread.currentThread().isInterrupted()); + + if (Thread.currentThread().isInterrupted()) { // 该值为读取 线程中断状态,不会改变中断状态的值 + System.out.println("结束线程..."); + stop = true; + } + + try { + Thread.sleep(1); //sleep + } catch (InterruptedException e) { + e.printStackTrace(); + //异常被捕获后 Thread.currentThread().isInterrupted() 值 将变为false + System.out.println("结束线程1...?"+Thread.currentThread().isInterrupted()); + Thread.currentThread().interrupt(); + System.out.println("结束线程2...?"+Thread.currentThread().isInterrupted()); + stop = true; + } + //线程中断操作 循环中使用 --End + } + + System.out.println("My Thread exiting under request..."); +} +}
\ No newline at end of file |
