Java中断线程

中断线程的方式

  1. 使用退出标志,使线程正常退出,也就是当run方法完成后线程终止。 
  2. 使用stop方法强行终止线程(这个方法不推荐使用,因为stop和suspend、resume一样,也可能发生不可预料的结果)。
  3.  使用interrupt方法中断线程

Java线程调度机制

https://blog.csdn.net/sdp1103285470/article/details/93602329

nterrupt()方法用于中断一个线程,而Java中线程的处理是协作式的而不是抢占式的。所谓协作式的意思是:实际上调用一个线程的interrupt() 方法中断一个线程,并不是强行关闭这个线程,只是跟这个线程打个招呼,将线程的中断标志位置为true,线程是否中断,由线程本身决定。
原文链接:https://blog.csdn.net/tianjindong0804/article/details/105134182

三个方法:

interrupt方法():

interrupt方法是用于中断线程的,调用该方法的线程的状态将被置为"中断"状态。注意:线程中断仅仅是设置线程的中断状态位,不会停止线程。需要用户自己去监视线程的状态为并做处理。

简单的说,只是给设置值,之后在由程序员监视这个值的变化,如果发现中断标志为true,就自定义处理逻辑

isInterrupted() :判定指定线程是否处于中断状态。

    public boolean isInterrupted() {
        return isInterrupted(false);
    }

static interrupted() :静态方法,判定当前线程是否处于中断状态,同时将中断标志位改为false。

   public static boolean interrupted() {
        return currentThread().isInterrupted(true);
    }

isInterrupted()和interrupted()都调用了同一个方法

/**
 * Tests if some Thread has been interrupted.  The interrupted state
 * is reset or not based on the value of ClearInterrupted that is
 * passed.
 */
private native boolean isInterrupted(boolean ClearInterrupted);

这是一个native方法,看不到源码没有关系,参数名字ClearInterrupted已经清楚的表达了该参数的作用----是否清除中断状态。方法的注释也清晰的表达了“中断状态将会根据传入的ClearInterrupted参数值确定是否重置”。所以,静态方法interrupted将会清除中断状态(传入的参数ClearInterrupted为true),而实例方法isInterrupted则不会(传入的参数ClearInterrupted为false)。 

 阻塞线程与线程中断

package com.basepackage.thread;

public class ThreadTerminal {
	public static void main(String[] args) throws Exception {
		Thread thread = new Thread(new TestRunnable1());
		thread.start();
		thread.interrupt();
		thread.interrupt();
		System.out.println("************************");
	}
}

class TestRunnable1 implements Runnable {

	@Override
	public void run() {
		try {
			Thread.sleep(3);
		} catch (InterruptedException e) {
			System.out.println("TestRunnable1中断标志:" + Thread.currentThread().isInterrupted());
			e.printStackTrace();
		}
		System.out.println("TestRunnable stop");

	}

}

 

我们在main里面调用了中断方法interrupt(),已经中断了,为什么中断标志是false?

Java中断响应是描述当一个线程或方法A处于运行、阻塞或死锁状态时,外界(通常指其他线程、系统IO等)对A的影响能否让A线程或者方法抛出InterruptedException异常并提前返回,如果会提前返回并且抛出InterruptedException,就叫可中断响应方法或线程,如果不会抛出InterruptedException,就叫不可中断线程或方法。

Java语言中所有阻塞方法都声明抛出InterruptedException异常(例如 Thread.sleep()、 Thread.join() 或 Object.wait())。也就是说,如果一个线程执行了阻塞方法,使得当前线阻塞,第三方线程执行interrupt方法中断线程,都会使得该阻塞方法抛出InterruptedException异常并退出阻塞,并且将当前线程的中断标志位设置为false。

如果没有这个机制, interrupt() 则只是单纯设置线程的中断状态。那这个试图中断的线程仍在阻塞当中,那么后序的中断工作则无法进行。


中断标志并不能停止线程,停止线程需要程序员手动控制

package com.basepackage.thread;

public class ThreadTerminal {
	public static void main(String[] args) throws Exception {

		Thread thread2 = new Thread(new TestRunnable2());
		thread2.start();
		thread2.interrupt();
		System.out.println("Main Stop");

	}
}

class TestRunnable2 implements Runnable {

	@Override
	public void run() {
		// 注意:线程中断仅仅是置线程的中断状态位,不会停止线程。需要用户自己去监视线程的状态为并做处理。支持线程中断的方法(也就是线程中断后会抛出interruptedException
		// 的方法)
		// 就是在监视线程的中断状态,一旦线程的中断状态被置为“中断状态”,就会抛出中断异常。
		// 这里由于没有监视中断标志,所以即使中断标志为true,线程也不会停止
		int i = 0;
		while (true) {
           System.out.println("TestRunnable1中断标志:" + Thread.currentThread().isInterrupted());
			System.out.println(i++);
		}
	}

}

我们仅仅发出中断信号,但是并不监视信号,那么就仅仅是给线程的中断标志设置为true,并不能停止线程

package com.basepackage.thread;

public class ThreadTerminal {
	public static void main(String[] args) throws Exception {
		System.out.println("************************");
		Thread thread3 = new Thread(new TestRunnable3());
		thread3.start();
		Thread.sleep(30);
		thread3.interrupt();

		System.out.println("************************");
	}
}


class TestRunnable3 implements Runnable {

	@Override
	public void run() {
		int i = 0;
		// 中断标志为false,代表线程没有中断
		while (Thread.currentThread().isInterrupted() == false) {
			System.out.println(i++);
		}
		System.out.println("线程停止");
	}

}

而此例我们通过Thread.currentThread().isInterrupted() == false监视中断标志,所以才能停止线程

interrupted的例子

package com.basepackage.thread;

public class ThreadTerminal {
	public static void main(String[] args) throws Exception {

		System.out.println("************************");
		Thread thread4 = new Thread(new TestRunnable4());
		thread4.start();
		Thread.sleep(30);
		thread4.interrupt();
		System.out.println("Main Stop");
	}
}


class TestRunnable4 implements Runnable {

	@Override
	public void run() {
		int i = 0;
		// 中断标志为false,代表线程没有中断
		// 如果未中断,判断Thread.currentThread().isInterrupted() == false成立,
		// 如果已经中断Thread.currentThread().interrupted()处理,之后又会将中断标志设置为false,
		// 之后的循环Thread.currentThread().isInterrupted() == false又再次成立,所以循环永远不会终止
		while (true) {
			if (Thread.currentThread().isInterrupted() == false) {
				System.out.println(i++);
			} else {
				System.out.println(Thread.interrupted());
			}

		}
	}

}

当main方法调用interrupt停止线程的时候,我们可以调用interrupted重置标志,所以才会一直输出,不会停止

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值