Thread.currentThread()与this的区别
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Thread.currentThread()与this的区别相关的知识,希望对你有一定的参考价值。
Thread.currentThread()与this的区别:
1.Thread.currentThread().getName()方法返回的是对当前正在执行的线程对象的引用,this代表的是当前调用它所在函数所属的对象的引用。
2.使用范围:
Thread.currentThread().getName()在两种实现线程的方式中都可以用。
this.getName()只能在继承方式中使用。因为在Thread子类中用this,this代表的是线程对象。
如果你在Runnable实现类中用this.getName(),那么编译错误,因为在Runnable中,不存在getName方法。
demo1:
public class MyThread extends Thread{
@Override
public void run(){
System.out.println("run currentThread.isAlive()=" + Thread.currentThread().isAlive());
System.out.println("run this.isAlive()=" + this.isAlive());
System.out.println("run currentThread.getName()=" + Thread.currentThread().getName());
System.out.println("run this.getName()=" + this.getName());
}
}
运行Run.java如下:
public class Run {
public static void main(String[] args) {
MyThread mythread = new MyThread();
mythread.setName("A");
System.out.println("begin main==" + Thread.currentThread().isAlive());
System.out.println("begin==" + mythread.isAlive());
mythread.start();
System.out.println("end==" + mythread.isAlive());
}
}
运行结果:
begin main==true
begin==false
end==true
run currentThread.isAlive()=true
run this.isAlive()=true
run currentThread.getName()=A
run this.getName()=A
demo2:
public class MyThread extends Thread{
@Override
public void run(){
System.out.println("run currentThread.isAlive()=" + Thread.currentThread().isAlive());
System.out.println("run this.isAlive()=" + this.isAlive());
System.out.println("run currentThread.getName()=" + Thread.currentThread().getName());
System.out.println("run this.getName()=" + this.getName());
}
}
运行Run.java如下:
public class Run {
public static void main(String[] args) {
MyThread mythread = new MyThread();
Thread t1 = new Thread(mythread);
t1.setName("A");
System.out.println("begin main==" + Thread.currentThread().isAlive());
System.out.println("begin==" + mythread.isAlive());
t1.start();
System.out.println("end==" + mythread.isAlive());
}
}
运行结果:
begin main==true
begin==false
end==false
run currentThread.isAlive()=true
run this.isAlive()=false
run currentThread.getName()=A
run this.getName()=Thread-0
以上是关于Thread.currentThread()与this的区别的主要内容,如果未能解决你的问题,请参考以下文章
Thread.currentThread()与this的区别,以及super.run()的作用
Java多线程之this与Thread.currentThread()的区别
Thread.currentThread()。interrupt()与来自Runnable#run()内的this.interrupt()
为啥在实现 Runnable 时使用 Thread.currentThread().isInterrupted() 而不是 Thread.interrupted()?