多线程学习(三):isAlive()和sleep()和getId()

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fengsheng5210/article/details/85057556

isAlive()

isAlive()判断线程是否处于活动状态,即线程已经启动但尚未终止。

例一

public class MyThread extends Thread{
	@Override
	public void run() {
		System.out.println("run="+this.isAlive());
	}
	public static void main(String[] args) throws InterruptedException {
		MyThread myThread = new MyThread();
		System.out.println("myThread还未运行,所以结果是false:"+myThread.isAlive());
		myThread.start(); //对象自我调度,所以this.isAlive()是存活的
		Thread.sleep(1000);
		System.out.println("myThread应该运行结束,所以结果是true:"+myThread.isAlive());
	}
}

运行结果

在这里插入图片描述

例二

public class MyThread02 extends Thread{
	//构造方法
	public MyThread02() {
		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方法结束");
	}
	public static void main(String[] args) throws InterruptedException {
		MyThread02 myThread=new MyThread02();
		Thread t1=new Thread(myThread); //myThread被t1调度,所以this.isAlive()不是存活的
		System.out.println("start t1....isAlive = "+t1.isAlive());
		t1.setName("A");
		t1.start();
		Thread.sleep(1000);
		System.out.println("end t1....isAlive = "+t1.isAlive());
	}
}

在这里插入图片描述

sleep()

sleep()的作用是在指定的毫秒数内让当前“正在执行的线程”休眠,“正在执行的线程”指this.currentThread()返回的线程,注意不是this,因为继承了Thread类,不一定就是this自己调度当前线程,可能当前对象构造传入给Thread t1,t1.start(),则t1才是“正在执行的线程”。

在这里插入图片描述
在这里插入图片描述

getId()

getId()方法的作用是取得线程的唯一标识

在这里插入图片描述


猜你喜欢

转载自blog.csdn.net/fengsheng5210/article/details/85057556