Thread中的isInterrupted()与interrupted()

惯例,先看源码中是如何定义的:两个方法是在Thread.class中定义的,其中

private native boolean isInterrupted(boolean ClearInterrupted);

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

interrupted()是静态方法:内部实现是调用的当前线程的isInterrupted(),并且会重置当前线程的中断状态,调用原生native方法,并设ClearInterrupted标志位为true,将状态清除;

isInterrupted()是实例方法,是调用该方法的对象所表示的那个线程的isInterrupted(),不会重置当前线程的中断状态,因为没有将ClearInterrupted标志位置位true,而是false,不清空状态;

例子可以根据下面这个去理解:

/**
 * 
 * @author Chain
 * 
 * 注意,多次运行结果可能不同,因为t1的状态可能不同,可能处于BLOCKED状态,则interrupted为true;假如为TERMINATED状态的话,那么interrupted就为false了
 *
 */
public class interruptedTest implements Runnable{
	@Override
	public void run() {
		// TODO Auto-generated method stub
//		设置中断监听 Stop函数停止线程过于暴力,会发生数据不一致现象,加入发生这种现象就会影响系统的运行
//		安全停止线程的两方法:    循环标记变量  或  循环中断状态
		while(!Thread.currentThread().isInterrupted()) {
			
		}
		System.out.println("thread do something");
		System.out.println("--------------------");
	}
	
	public static void main(String[] args) throws InterruptedException {
		Thread t1 = new Thread(new interruptedTest());
		t1.start();
		
//		Thread.sleep(1000);
		//t1线程 使用isInterrupted
		t1.interrupt();
		System.out.println("t1  is interrupted ?: "+t1.isInterrupted()+"----t1's name:  "+t1.getName()+"----t1's state:  "+t1.getState());
		System.out.println("t1  is interrupted ?: "+t1.isInterrupted()+"----t1's name:  "+t1.getName()+"----t1's state:  "+t1.getState());
		
		
		//main主线程 测试 interrupted
		Thread.currentThread().interrupt();
		System.out.println("main  is interrupted ?: "+Thread.interrupted());
		System.out.println("main  is interrupted ?: "+Thread.interrupted());
		
	}

	
}

 

你可能感兴趣的:(java基础)