您的位置:首页 > 其它

多线程中this、Thread.currentThread()和this.currentThread()的区别

2016-03-14 15:55 525 查看
this指的是当前对象,而Thread.currentThread()指的是当前运行的线程对象,这两者有时不一定相同。

如下列代码所示

public class CountOperate extends Thread{
public CountOperate(){
System.out.println("CountOperate---begin");
System.out.println("current name is "+Thread.currentThread().getName());
System.out.println("Thread.currentThread().isAlive()="+Thread.currentThread().isAlive());
System.out.println("this name is "+this.getName());
System.out.println("this.isAlive()="+this.isAlive());
System.out.println("CountOperate---end");
}

}

main函数

public class Run {
public static void main(String[] args) {
// TODO Auto-generated method stub
CountOperate c = new CountOperate();
Thread t1 = new Thread(c);
}

}

输出结果



Thread.currentThread()和this.currentThread()在大部分情况下结果是相同的,都是调用Thread的静态方法currentThread(),若当前子类重写了父类的currentThread()方法,那么Thread.currentThread()和this.currentThread()返回的结果会不同。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: