interrupt ,interrupted,isInterrupted 区别

 

 

一、interrupt 
interrupt方法用于中断线程。调用该方法的线程的状态为将被置为"中断"状态。
注意:线程中断仅仅是置线程的中断状态位,不会中止线程。须要用户本身去监视线程的状态为并作处理。支持线程中断的方法(也就是线程中断后会抛出interruptedException的方法)就是在监视线程的中断状态,一旦线程的中断状态被置为“中断状态”,就会抛出中断异常。java

2.interrupted 是做用于当前线程,isInterrupted 是做用于调用该方法的线程对象所对应的线程。(线程对象对应的线程不必定是当前运行的线程。例如咱们能够在A线程中去调用B线程对象的isInterrupted方法。)
这两个方法最终都会调用同一个方法,只不过参数一个是true,一个是false;
这两个方法很好区分,只有当前线程才能清除本身的中断位(对应interrupted()方法)ide

 

package com.famous.thread;

public class ThreadStopDemo {

	/**
	 * 
	 * mock thread stop
	 * 
	 * @author zhenglong
	 *
	 */
	public static void main(String[] args) {

		Thread thread = new Thread(new StopThread());
		thread.start();
		try {
			Thread.sleep(100);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		thread.interrupt();
	}

	static class StopThread implements Runnable {

		@Override
		public void run() {
			int i = 0;
			while (true) {
				i++;
				System.err.println(i);
				if (Thread.currentThread().isInterrupted()) {
					// 一直输出true
					System.err.println(Thread.currentThread().isInterrupted());
					// 一直输出true
					System.err.println(Thread.currentThread().isInterrupted());
					// 一直输出true
					System.err.println(Thread.currentThread().interrupted());
					// 一直输出false
					System.err.println(Thread.currentThread().interrupted());
					break;
				}
			}
		}
	}
}
相关文章
相关标签/搜索