线程 Interrupter 使用要注意的问题

package com.thread;


public class InterrupterDemo {


/**
* @param args
*/
public static void main(String[] args) throws InterruptedException {
MyThread ta = new MyThread();
ta.setName("ThreadA");
ta.start();
Thread.sleep(2000);
System.out.println(ta.getName() + "正在被中断...");
ta.interrupt();// 这样终止有问题 发生InterruptedException
// this.isInterrupted()又会变为false,while循环又继续执行了


// 应该这样使用
ta.interrupt();
System.out.println("ta.isInterrupted()=" + ta.isInterrupted());


}


}


class MyThread extends Thread {
int count = 0;


boolean isinterruptre = false;


public void interrupt() {
isinterruptre = true;
super.interrupt();
}


public void run() {
System.out.println(getName() + "将要运行...");
while (/* !this.isInterrupted() */isinterruptre) {
System.out.println(getName() + "运行中" + count++);
try {
Thread.sleep(400);
} catch (InterruptedException e) {
System.out.println(getName() + "从阻塞中退出...");
System.out.println("this.isInterrupted()=" + this.isInterrupted());


}
}
System.out.println(getName() + "已经终止!");
}
}

你可能感兴趣的:(学习笔记)