Interrupt、Interrupted、IsInterrupted

1、interrupt() 
interrupt方法用于中断线程。调用该方法的线程的状态为将被置为"中断"状态。
注意:线程中断仅仅是置线程的中断状态位,不会停止线程。需要用户自己去监视线程的状态为并做处理。
 
2、interrupted() 和 isInterrupted()
 
private native boolean isInterrupted( boolean ClearInterrupted);

  

public static boolean interrupted () {
  //清除标记位
return currentThread().isInterrupted(true); }
public boolean isInterrupted () {
  //不清除标记位直接返回
return isInterrupted(false); } 

如果这个参数为true,说明返回线程的状态位后,要清掉原来的状态位(恢复成原来情况)。

class Example2 extends Thread {
    public static void main(String args[]) throws Exception {
        Example2 thread = new Example2();
        System.out.println("Starting thread...");
        thread.start();
        Thread.sleep(3000);
        System.out.println("Asking thread to stop...");
        // 发出中断请求
        thread.interrupt();
        Thread.sleep(3000);
        System.out.println("Stopping application...");
    }

    public void run() {
        // 每隔一秒检测是否设置了中断标示
        while (!Thread.currentThread().isInterrupted()) {
            System.out.println("Thread is running...");
            long time = System.currentTimeMillis();
            // 使用while循环模拟 sleep
            while ((System.currentTimeMillis() - time < 1000) ) {
            }
       /*
       try{sleep(1000);}catch(InterruptException e){e.printStackTrace();}
       */
        }
        System.out.println("Thread exiting under request...");
    }
}

  

原文地址:https://www.cnblogs.com/lnas01/p/7896169.html