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;
				}
			}
		}
	}
}
相關文章
相關標籤/搜索