java线程的中断(interrupt)

1.中断原理

java中断并非直接中断线程的运行,中断只是一种协作机制,每个线程底层都保留一个中断标志符,程序可以调用中断方法,但是是否真正的中断还是依赖于应用程序本身的处理,中断有对应2种情况,在线程阻塞时,对于某些特别的阻塞,例如Thread方法的sleep,Object的wait方法,以及一些nio的阻塞,阻塞队列的take方法等,如果在阻塞的状态下调用interrupt()方法,会导致抛出InterruptedException异常,并重置其中断状态,即为false。而在另一些常规的IO阻塞和同步阻塞,设置中断,都只会改变其中断状态,程序可以处理,也可以不处理。

下面的三个方法都是Thread类的。

中断相关方法作用
interrupt()设置线程中断的唯一方法
interrupted()静态方法,获取当前线程是否中断的方法,获取之后中断状态将会被重置,例如调用interrupt()方法,再调用interrupted()方法会返回true,第二次调用会返回false,因为中断的状态被重置了。
isInterrupted()返回线程的中断状态,中断不会被此方法改变。

2.实例

package com.thread.study;

import com.util.GeneryUtil;

public class InterruptTest implements Runnable{

	@Override
	public void run() {
		try {
			while(true) {

			}
		} catch (Exception e) {
			GeneryUtil.outputConsole("interrupt Exception");
		}

	}


	public static class InterruptTest2 implements Runnable{

		@Override
		public void run() {
			System.out.println("this is InterruptTest2");
			try {
				Thread.sleep(10000);
			} catch (InterruptedException e) {
				System.out.println("InterruptedException of InterruptTest2");
				e.printStackTrace();
			}
		}
	}

	public static class InterruptTest3 implements Runnable{

		@Override
		public void run() {
			System.out.println("this is InterruptTest3");
			synchronized (this){
				try {
					this.wait();
				} catch (InterruptedException e) {
					System.out.println("InterruptedException of InterruptTest3");
				}
			}
		}
	}


	public static void main(String[] args) throws InterruptedException {
		Thread t1 = new Thread(new InterruptTest());
		Thread t2 = new Thread(new InterruptTest2());
		Thread t3 = new Thread(new InterruptTest3());
		t1.start();
		t2.start();
		t3.start();
		Thread.sleep(3000);
		Thread.currentThread().interrupt();
		t2.interrupt();
		t3.interrupt();
		System.out.println("first get interrupt of status of t1:"+Thread.currentThread().interrupted());
		System.out.println("second get interrupt of status of t1:"+Thread.currentThread().interrupted());
		System.out.println("second get interrupt of status of t1 by isInterrupted's method "+Thread.currentThread().isInterrupted());



	}

	
}


在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值