暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

currentThread()和this区别

面向对象的隔壁老王 2016-11-06
234

我们来看如下代码:

public class MyTest {


public static void main(String[] args) {

MyThread myThread = new MyThread();

Thread thread=new Thread(myThread);

System.out.println("main begin thread isAltive="+thread.isAlive());

thread.setName("老王一号");

thread.start();

System.out.println("main end thread isAltive="+thread.isAlive());

}

}

class MyThread extends Thread{

public MyThread(){

System.out.println("MyThread——begin");

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("MyThread——end");

}


@Override

public void run() {

super.run();

System.out.println("run——begin");

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——end");

}

}

运行结果:


首先解释一下,isAltive()方法:判断当前的线程是否处于活动状态,也就是线程已经启动且尚未终止,线程处于正在运行或准备运行的状态。


这个例子和运行的结果,详细的区分了this表示的是当前类,而currentThread()为当前线程。

文章转载自面向对象的隔壁老王,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论