Java教程-中断线程

中断线程
如果任何线程处于睡眠或等待状态(即调用了sleep()或wait()方法),在该线程上调用interrupt()方法会打破睡眠或等待状态,并抛出InterruptedException。如果线程不处于睡眠或等待状态,调用interrupt()方法会执行正常的行为,不会中断线程,但会将中断标志设置为true。首先让我们看一下Thread类提供的用于中断线程的方法。
Thread类提供的3个中断线程的方法:
- public void interrupt()
- public static boolean interrupted()
- public boolean isInterrupted()
中断正在工作的线程的示例
在此示例中,在中断线程之后,我们传播了异常,所以它将停止工作。如果我们不想停止线程,我们可以在调用sleep()或wait()方法的地方处理它。首先让我们看一个传播异常的示例。
TestInterruptingThread1.java
class TestInterruptingThread1 extends Thread{
public void run(){
try{
Thread.sleep(1000);
System.out.println("task");
}catch(InterruptedException e){
throw new RuntimeException("Thread interrupted..."+e);
}
}
public static void main(String args[]){
TestInterruptingThread1 t1=new TestInterruptingThread1();
t1.start();
try{
t1.interrupt();
}catch(Exception e){System.out.println("Exception handled "+e);}
}
}
输出:
Exception in thread-0
java.lang.RuntimeException: Thread interrupted...
java.lang.InterruptedException: sleep interrupted
at A.run(A.java:7)
不会停止工作的线程中断示例
在此示例中,在中断线程之后,我们处理了异常,所以它会退出睡眠状态,但不会停止工作。
TestInterruptingThread2.java
class TestInterruptingThread2 extends Thread{
public void run(){
try{
Thread.sleep(1000);
System.out.println("task");
}catch(InterruptedException e){
System.out.println("Exception handled "+e);
}
System.out.println("thread is running...");
}
public static void main(String args[]){
TestInterruptingThread2 t1=new TestInterruptingThread2();
t1.start();
t1.interrupt();
}
}
输出:
Exception handled
java.lang.InterruptedException: sleep interrupted
thread is running...
行为正常的线程中断示例
如果线程不处于睡眠或等待状态,调用interrupt()方法会将中断标志设置为true,由Java程序员稍后使用该标志来停止线程。
TestInterruptingThread3.java
class TestInterruptingThread3 extends Thread{
public void run(){
for(int i=1;i<=5;i++)
System.out.println(i);
}
public static void main(String args[]){
TestInterruptingThread3 t1=new TestInterruptingThread3();
t1.start();
t1.interrupt();
}
}
输出:
1
2
3
4
5
isInterrupted和interrupted方法如何使用?
isInterrupted()方法返回中断标志,可以是true或false。静态的interrupted()方法在返回中断标志后,如果标志为true,则将其设置为false。
TestInterruptingThread4.java
public class TestInterruptingThread4 extends Thread{
public void run(){
for(int i=1;i<=2;i++){
if(Thread.interrupted()){
System.out.println("code for interrupted thread");
}
else{
System.out.println("code for normal thread");
}
}//for 循环结束
}
public static void main(String args[]){
TestInterruptingThread4 t1=new TestInterruptingThread4();
TestInterruptingThread4 t2=new TestInterruptingThread4();
t1.start();
t1.interrupt();
t2.start();
}
}
输出:
Code for interrupted thread
code for normal thread
code for normal thread
code for normal thread