首页 > 代码库 > Thread.currentThread()与this的区别

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的区别