Thread线程的理解

2019-02-23  本文已影响0人  chase_

sleep()方法

该方法是让线程睡眠,注意睡眠的线程是当前执行的线程,如下代码,睡眠的是main线程,不是t1线程,如果要让t1睡眠,sleep的位置应该是在A線程裏面的run()方法,并且sleep是静态方法,调用不应该用实例调用,应该是Thread.sleep(),别让t1.sleep()的方法误导,误以为是t1线程睡眠。

package com.xxl.rpc.test;

public class Interrupt {


    public static void main(String[] args) {
        A a = new A();
        Thread t1 = new Thread(a);
        t1.start();
        System.out.println("执行睡眠之前2:" + t1.isInterrupted());
        try {
            t1.sleep(2000);//线程进入阻塞状态
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(123);
    }
}

class A implements Runnable {

    @Override
    public void run() {
        long now = System.currentTimeMillis();
        boolean flag = true;
        while (System.currentTimeMillis() - now < 1000) {
            System.out.println(222);
        }
    }
}



线程的中断

主要涉及到三个方法,如下
1.public void interrupt():中断该线程
2.public static boolean interrupted() 返回该线程的中断状态,并清除中断状态,该方法其实是调用了另一个中断方法private native boolean isInterrupted(boolean ClearInterrupted),ClearInterrupted为ture,标识清楚中断标志。
3.public boolean isInterrupted() {
return isInterrupted(false);
}返回线程的中断状态,但是不清楚中断状态。

线程的中断是会唤醒sleep、wait、join中的线程,也就是说会让这些方法抛出InterruptedException异常,从而唤醒线程,如下代码

package com.xxl.rpc.test;

public class Interrupt {


    public static void main(String[] args) {
        Thread b = new B();
        b.start();
        b.interrupt();
    }
}

class B extends Thread {

    @Override
    public void run() {
        System.out.println("do something");
        try {
            System.out.println("线程中断状态"+this.isInterrupted());
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            //false说明抛出异常导致中断状态被清除
            System.out.println("线程中断状态"+this.isInterrupted());
            System.out.println("中断抛出的异常");
            //do something else
        }

    }
}

执行结果如下:
do something
线程中断状态true
线程中断状态false
中断抛出的异常

Process finished with exit code 0

上一篇 下一篇

猜你喜欢

热点阅读