Java多线程中interrupt interrupted isInterrupted

/**
 * Created by wangxizhong on 17/4/13.
 */
public class Main {
    public static void main(String[] args) throws InterruptedException {
        MyThread thread = new MyThread();
        thread.start();
        thread.interrupt();
        //Thread.currentThread().interrupt();
        System.out.println("是否停止1?========================="+thread.interrupted());//false
        System.out.println("是否停止2?=========================="+thread.interrupted());//false main线程没有被中断!!!
        System.out.println("是否停止3?========================="+thread.isInterrupted());//true thread线程被中断!!!
        System.out.println("是否停止4?========================="+thread.isInterrupted());//true thread线程被中断!!!
    }
}

/**
 * Created by wangxizhong on 17/4/13.
 */
public class MyThread extends Thread {
    public void run() {
       // if(!interrupted()) {
            for (int x = 0; x < 10000; x++) {
                System.out.println("x=" + x);
               // System.out.println(interrupted());//this 线程被中断 true   ---当第二次循环的时候会变为false
            }
       // }else {
        //    return;
       // }
    }
}

interrupted  检测线程是否是中断状态,执行后具有将状态标识清除为false的功能   用作检测当前线程

isInterrupted  不会清除标识状态   测试线程对象是否已经是中断状态  用于调用该方法线程对象所对应的线程  上文中调用者为主线程main



你可能感兴趣的:(Java随记)