java 中断线程 wait,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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值