1、线程之isAlive的使用和理解

2017-05-16  本文已影响0人  DesertSnow
public class TestIsAlive {
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + "====start=====" + myThread.isAlive());
        myThread.start();
       //  start
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // end
        System.out.println(Thread.currentThread().getName() + "=====end====" + myThread.isAlive());
    }
}

class MyThread extends Thread {
    public MyThread() {
        System.out.println(Thread.currentThread().getName() + "======构造函数======" + this.getName());
        System.out.println(Thread.currentThread().getName() + "=====构造函数====" + this.isAlive());
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "======run方法======" + this.getName());
        System.out.println(Thread.currentThread().getName() + "====run方法=====" + this.isAlive());
    }
}


执行结果如下:
main======构造函数======Thread-0
main=====构造函数====false
main====start=====false
Thread-0======run方法======Thread-0
Thread-0====run方法=====true
main=====end====false

如果把// start和//end中间的代码全注释掉,执行结果如下:
main======构造函数======Thread-0
main=====构造函数====false
main====start=====false
main=====end====true
Thread-0======run方法======Thread-0
Thread-0====run方法=====true
上一篇 下一篇

猜你喜欢

热点阅读