this:
this关键字指向的是当前对象的引用,主要有三个应用:
1 this调用本类中的属性,也就是类中的成员变量;
2 this调用本类中的其他方法;
3 this调用本类中的其他构造方法,调用时要放在构造方法的首行。
Thread.currentThread:
currentThread() 只是Thread 的一个静态方法。返回的正是执行当前代码指令的线程引用,源码如下:
/**
* Returns a reference to the currently executing thread object.
*
* @return the currently executing thread.
*/
public static native Thread currentThread();
测试用例:
public class MyThread extends Thread {
public MyThread(){
System.out.println("---MyThread begin---");
// Thread.currentThread() 代表的是主线程main
System.out.println("Thread.currentThread.getName()="+Thread.currentThread().getName());
// 主线程main 的处在正在运行中,状态为RUNNABLE ,所以Thread.currentThread().isAlive() 为true
System.out.println("Thread.currentThread().isAlive()="+Thread.currentThread().isAlive());
// this 指的是当前实例对象tt,名称系统自动给出Thread-0
System.out.println("this.getName()="+this.getName());
// 由于没有启动,所以this.isAlive())是false
System.out.println("this.isAlive()="+this.isAlive());
// Thread.currentThread()和this是两个不同的实例对象
System.out.println(Thread.currentThread()==this);
System.out.println("---MyThread begin---");
}
@Override
public void run(){
System.out.println("---run begin---");
// Thread.currentThread(). 指的是t1
System.out.println("Thread.currentThread.getName()="+Thread.currentThread().getName());
// t1正在运行,其状态为true
System.out.println("Thread.currentThread().isAlive()="+Thread.currentThread().isAlive());
// // this 指的是当前实例对象tt,名称系统自动给出Thread-0,由于没有启动状态是false
System.out.println("this.getName()="+this.getName());
System.out.println("this.isAlive()="+this.isAlive());
System.out.println(Thread.currentThread()==this);
System.out.println("---run end ---");
}
public static void main(String[] args) throws InterruptedException{
// 创建 MyThread 实例对象tt,执行构造函数MyThread()
MyThread tt =new MyThread();
/* 创建Thread 对象t1,设置name为test,并将tt绑定到target 源码如下:
* public Thread(Runnable target) {
* init(null, target, "Thread-" + nextThreadNum(), 0);
* }
*/
Thread t1 =new Thread(tt);
t1.setName("test");
// t1.start() 其实质就是调用了target:tt的run()方法。
t1.start();
}
}
运行结果如下:
总结:
1 线程是可以嵌套的,如上述代码 Thread t1 =new Thread(tt)。
2 调用start方法方可启动线程,而run方法只是thread的一个普通方法调用,还是在主线程里执行。
3 由Thread源码:class Thread implements Runnable 可知,继承Thread和实现Runnable来创建线程工作时没有本质的区别。只是java语言规定类只能单继承,但是可以实现多个类,所以在实际开发过程中,还是建议用实现Runnable或者创建线程池 的方式创建线程。