Thread.currentThread()与this的区别

it2022-05-05  187

Thread.currentThread()与this的区别

1.Thread.currentThread()方法返回的是对当前正在执行的线程对象的引用,this代表的是当前调用它所在函数所属的对象的引用。

2.使用范围:

   Thread.currentThread()在两种实现线程的方式中都可以用。   this只能在继承方式中使用。因为在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

 

转载于:https://www.cnblogs.com/meizizhoushan/p/7282551.html


最新回复(0)