The role of the Java isalive() method

Example 1

package ch14;
public class MyThread08 extends Thread
{
    @Override 
    public void run()
    { 
        System.out.println("run="+this.isAlive()); 
    }
}
package ch14;
public class Test11
{
    public static void main(String[] args)
    {
        MyThread08 mythread=new MyThread08();    //创建一个MyThread08线程实例
        System.out.println("begin=="+mythread.isAlive());    //输出线程状态
        mythread.start();    //启动线程
        System.out.println("end=="+mythread.isAlive());    //输出线程状态
    }
}
begin==false
end==true
run=true
System.out.println("end=="+mythread.isAlive());
package ch14;
public class Test11
{
    public static void main(String[] args) throws InterruptedException
    { 
        MyThread08 mythread=new MyThread08();    //创建一个MyThread08线程实例
        System.out.println("begin=="+mythread.isAlive());    //输出线程状态
        mythread.start();    //启动线程
        Thread.sleep(1000);     //延时1000毫秒
        System.out.println("end=="+mythread.isAlive());    //输出线程状态
    }
}
begin==false
run=true
end==false

Example 2

package ch14;
public class MyThread09 extends Thread
{
    public MyThread09()
    {
        System.out.println("构造方法---开始");
        System.out.println("Thread.currentThread().getName()="+Thread.currentThread().getName());
        System.out.println("Thread.currentThread().isAlive()="+Thread.currentThread().isAlive());
        System.out.println("this.getName()="+this.getName());
        System.out.println("this.isAlive()="+this.isAlive());
        System.out.println("构造方法---结束");
    }
    @Override
    public void run()
    {
        System.out.println("run()方法---开始");
        System.out.println("Thread.currentThread().getName()="+Thread.currentThread().getName());
        System.out.println("Thread.currentThread().isAlive()="+Thread.currentThread().isAlive());
        System.out.println("this.getName()="+this.getName());
        System.out.println("this.isAlive()="+this.isAlive());
        System.out.println("run()方法---结束");
    }
}
package ch14;
public class Test12
{
    public static void main(String[] args)
    {
        MyThread09 mythread=new MyThread09();    //创建一个MyThread09线程实例
        Thread t1=new Thread(mythread);    //创建一个线程
        System.out.println("main begin t1 isAlive="+t1.isAlive());    //输出线程状态
        t1.setName("A");    //设置线程名称
        t1.start();    //启动线程
        System.out.println("main end t1 isAlive="+t1.isAlive());
    }
}
构造方法---开始
Thread.currentThread().getName()=main
Thread.currentThread().isAlive()=true
this.getName()=Thread-0
this.isAlive()=false
构造方法---结束
main begin t1 isAlive=false
main end t1 isAlive=true
run()方法---开始
Thread.currentThread().getName()=A
Thread.currentThread().isAlive()=true
this.getName()=Thread-0
this.isAlive()=false
run()方法---结束
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>