this.isAlive()与Thread.currentThread().isAlive() 的差异

public class MyThread extends Thread {

    public MyThread() {
        System.out.println(Thread.currentThread().getName()
                + " :: this.isAlive() :: " + this.isAlive());
        System.out.println(Thread.currentThread().getName()
                + " :: Thread.currentThread().isAlive() :: "
                + Thread.currentThread().isAlive());
    }

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

    /**
     * 在调用thread1.start()方法后,thread1的this.isAlive()==true;
     * 而将new Mythread()对象以参数的形势传入new Thread()构造器后,
     * 再调用thread2.start()方法后,thread2的this.isAlive()==false.
     */
    public static void main(String[] args) {
        MyThread thread1 = new MyThread();
        thread1.start();
        Thread thread2 = new Thread(new MyThread());
        thread2.start();
    }
}
  • 当直接调用线程对象的start()方法时,在run()方法中调用this.isAlive()true
  • 当将线程对象以构造函数参数的方式传递给Thread对象,调用该Thread对象的start()方法时,在run()方法中调用this.isAlive()false
  • 相比较之下run()方法中的Thread.currentThread().isAlive()一直为true
    运行结果

Java多线程编程核心技术 高洪岩著

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容