14.5 Interrupt中断的使用

来源:互联网 发布:网络远程教育大学 编辑:程序博客网 时间:2024/05/29 04:33
package cn.chen.interrupt;public class DemoInterrupt extends Thread{boolean flag = true;public DemoInterrupt(String name){super(name);}@Overridepublic synchronized void run() {int i =0;while(flag){try {this.wait();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();} System.out.println(Thread.currentThread().getName()+":"+i);i++;}}public static void main(String[] args) {// TODO Auto-generated method stubDemoInterrupt d = new DemoInterrupt("张三");d.setPriority(MAX_PRIORITY);d.start();for (int i = 0; i < 20; i++) {System.out.println(Thread.currentThread().getName()+":"+i);if(i == 8){d.flag =false;d.interrupt();//把线程的等待状态强制清除,被清除状态的线程会会收到一个interruptedException//方法比较粗暴//synchronized(d){//d.notify();//}}}}}

0 0
原创粉丝点击