美文网首页
this.isAlive()与Thread.currentThr

this.isAlive()与Thread.currentThr

作者: vygjyfjt | 来源:发表于2019-03-05 23:09 被阅读0次
    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多线程编程核心技术 高洪岩著

    相关文章

      网友评论

          本文标题:this.isAlive()与Thread.currentThr

          本文链接:https://www.haomeiwen.com/subject/xrwauqtx.html