个性化阅读
专注于IT技术分析

Java中断线程

本文概述

如果任何线程处于睡眠或等待状态(即调用sleep()或wait()), 则在该线程上调用interrupt()方法会中断睡眠或等待状态并抛出InterruptedException。如果线程未处于睡眠或等待状态, 则调用interrupt()方法将执行正常行为, 并且不会中断线程, 而是将中断标志设置为true。首先让我们看看Thread类提供的用于中断线程的方法。

Thread类提供的3种中断线程的方法

公共无效中断()公共静态布尔中断()公共布尔isInterrupted()

中断停止工作的线程的示例

在此示例中, 中断线程后, 我们正在传播该线程, 因此它将停止工作。如果我们不想停止线程, 则可以在调用sleep()或wait()方法的地方进行处理。首先让我们看一下传播异常的示例。
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);}

}
}

立即测试

Output:Exception in thread-0  
       java.lang.RuntimeException: Thread interrupted...
       java.lang.InterruptedException: sleep interrupted
       at A.run(A.java:7)

中断不停止工作的线程的示例

在此示例中, 在中断线程之后, 我们将处理异常, 因此它将打破睡眠状态, 但不会停止工作。
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();

}
}

立即测试

Output:Exception handled  
       java.lang.InterruptedException: sleep interrupted
       thread is running...

中断正常运行的线程的示例

如果线程未处于睡眠或等待状态, 则调用interrupt()方法会将interrupted标志设置为true, 以后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();

}
}

立即测试

Output:1
       2
       3
       4 
       5

那isInterrupted和interrupted方法呢?

isInterrupted()方法返回中断标志true或false。静态interrupted()方法将返回中断标志, 如果该标志为true, 则将标志设置为false。
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");
}

}//end of for loop
}

public static void main(String args[]){

TestInterruptingThread4 t1=new TestInterruptingThread4();
TestInterruptingThread4 t2=new TestInterruptingThread4();

t1.start();
t1.interrupt();

t2.start();

}
}

立即测试

Output:Code for interrupted thread
       code for normal thread
       code for normal thread
       code for normal thread
赞(0)
未经允许不得转载:srcmini » Java中断线程

评论 抢沙发

评论前必须登录!