package com.tony.app;
public class CountOperate extends Thread{
public CountOperate(){
System.out.println("CountOperate---begin");
// CountOperate构造方法由main线程调用
// currentThread() 返回代码段正在被哪个线程调用 main
System.out.println("Thread.currentThread().getName()=" + Thread.currentThread().getName());//获取线程名
// main线程还存活 所有返回true
System.out.println("Thread.currentThread().isAlive()=" + Thread.currentThread().isAlive()); //查看线程是否存活
// CountOperate 线程还未start
// Thread-0 ? 进入CountOperate构造方法前 会自动调用父类Thread的无参构造方法
System.out.println("this.getName=" + this.getName());
// isAlive() 判断当前线程是否处于活动状态 还未start 所以为false
System.out.println("this.isAlive()=" + this.isAlive());
System.out.println("CountOperate---end ");
// main == CountOperate ? false
System.out.println("Thread.currentThread()==this :"+ (Thread.currentThread() == this));
}
@Override
public void run() {
System.out.println("run---begin");
// A
System.out.println("Thread.currentThread().getName=" + Thread.currentThread().getName());
// true
System.out.println("Thread.currentThread().isAlive()" + Thread.currentThread().isAlive());
// this 代表CountOperate实例
// Thread.currentThread() 代表 t1
System.out.println("Thread.currentThread()==this :"+ (Thread.currentThread() == this));
System.out.println("this.getName()=" + this.getName());
System.out.println("this.isAlive()=" + this.isAlive());
System.out.println("run --- end");
}
}
package com.tony.app;
public class Run {
public static void main(String[] args){
CountOperate c = new CountOperate();
Thread t1 = new Thread(c);
// t1还没start fasle
System.out.println("main begin t1 isAlive=" + t1.isAlive());
t1.setName("A");
t1.start();
System.out.println("main end t1 isAlive=" + t1.isAlive());
}
}
结果:
CountOperate---begin
Thread.currentThread().getName()=main
Thread.currentThread().isAlive()=true
this.getName=Thread-0
this.isAlive()=false
CountOperate---end
Thread.currentThread()==this :false
main begin t1 isAlive=false
main end t1 isAlive=true
run---begin
Thread.currentThread().getName=A
Thread.currentThread().isAlive()true
Thread.currentThread()==this :false
this.getName()=Thread-0
this.isAlive()=false
run --- end
run()方法输出的解释:
CountOperate c = new CountOperate();
Thread t1 = new Thread(c);
代码中c并没有start()而是作为参数传递给t1的构造函数中的Runnable
也就是说c的run()是t1.start()后调用target中的run()方法执行的
而Thread.currentThread()返回的是代码段被哪个线程调用 这个线程正是t1 所以:
Thread.currentThread().getName=A // t1.getName便是A
Thread.currentThread().isAlive()true // t1此时正在运行 返回true
Thread.currentThread()==this :false // this代表c Thread.currentThread()指向t1 所以返回false
this.getName()=Thread-0 // c.getName()由c的构造方法中调用父类的无参构造方法时赋值的
this.isAlive()=false // c.isAlive() c作为线程并没有start() 所以c这个线程并没有启动 c的run()作为实例方法被t1调用了