线程的中断
在很多时候,我们需要在一个线程中调控另一个线程,这时我们就要用到线程的中断。用最简单的话也许可以说它就相当于播放机中的暂停一样,当第一次按下暂停时,播放器停止播放,再一次按下暂停时,继续从刚才暂停的地方开始重新播放。而在Java中,这个暂停按钮就是Interrupt()方法。在第一次调用interrupt()方法时,线程中断;当再一次调用interrupt()方法时,线程继续运行直到终止。这里依然引用《用线程获得强大功能》一文中的程序片断,但为了更方便看到中断的过程,我在原程序的基础上作了些改进,程序如下:
/* ===================================================================================
* 文件:ThreadDemo09.java
* 描述:线程的中断
* ===================================================================================
*/
class ThreadA extends Thread{
private Thread thdOther;
ThreadA(Thread thdOther){
this.thdOther = thdOther;
}
public void run(){
System.out.println(getName() + " 运行...");
int sleepTime = (int)(Math.random() * 10000);
System.out.println(getName() + " 睡眠 " + sleepTime
+ " 毫秒。");
try{
Thread.sleep(sleepTime);
}catch(InterruptedException e){}
System.out.println(getName() + " 觉醒,即将中断线程 B。");
// 中断线程B,线程B暂停运行
thdOther.interrupt();
}
}
class ThreadB extends Thread{
int count = 0;
public void run(){
System.out.println(getName() + " 运行...");
while (!this.isInterrupted()){
System.out.println(getName() + " 运行中 " + count++);
try{
Thread.sleep(10);
}catch(InterruptedException e){
int sleepTime = (int)(Math.random() * 10000);
System.out.println(getName() + " 睡眠" + sleepTime
+ " 毫秒。觉醒后立即运行直到终止。");
try{
Thread.sleep(sleepTime);
}catch(InterruptedException m){}
System.out.println(getName() + " 已经觉醒,运行终止...");
// 重新设置标记,继续运行
this.interrupt();
}
}
System.out.println(getName() + " 终止。");
}
}
class Test{
public static void main(String argv[]){
ThreadB thdb = new ThreadB();
thdb.setName("ThreadB");
ThreadA thda = new ThreadA(thdb);
thda.setName("ThreadA");
thdb.start();
thda.start();
}
}
运行以上程序,你可以清楚地看到中断的过程。首先线程B开始运行,接着运行线程A,在线程A睡眠一段时间觉醒后,调用interrupt()方法中断线程B,此是可能B正在睡眠,觉醒后掏出一个InterruptedException异常,执行其中的语句,为了更清楚地看到线程的中断恢复,我在InterruptedException异常后增加了一次睡眠,当睡眠结束后,线程B调用自身的interrupt()方法恢复中断,这时测试isInterrupt()返回true,线程退出。