java——线程中断使用范例2

2019年2月18日23:12:26 发表评论 1,156 views
/**
 * Created by xabcd on 2019/2/18.
 */
public class stopThread2
{
    public static void main(String args[])
    {
        Thread t = Thread.currentThread();
        //通过Thread类中的currentThread()方法取得当前运行的线程,因为此代码是在main()方法中运行,所以当前的线程就为main()线程。
        System.out.println("A.t.isInterrupted()="+t.isInterrupted());
        t.interrupt();
        System.out.println("B.t.isInterrupted()="+t.isInterrupted());
        System.out.println("C.t.isInterrupted()="+t.isInterrupted());
        try {
            Thread.sleep(2000);
            //让线程开始休眠,但此时线程已经被中断,所以这个时候会抛出中断异常,
            System.out.println("线程没有被中断");
        }
        catch (InterruptedException x){
            System.out.println("线程被中断");
        }
        //因为sleep抛出了异常,所以它清除了中断标志 结果返回false
        System.out.print("D.t.isInterrupted()="+t.isInterrupted());
    }

}

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: