示?1
class Test{
public static void main(String[] args) {
/**
* 1.创建CountOperate对象时,调用了该构造方法,此时是主线程执行构造方法的代码块,所以Thread.currentThread().getName()=main;
* this.getName()是获取当前线程实例(countOperate)的名字;如果未指定,默认为Thread-0
* 2.t1.start()启动线程,调用目标对象(countOperate)的run(),所以Thread.currentThread().getName()=A;如果未指定Thread的名字,默认为Thread-1
* this.getName()是获取当前线程实例(countOperate)的名字;如果未指定,默认为Thread-0
*/
//测试1
// CountOperate countOperate=new CountOperate();
//测试2
// CountOperate countOperate=new CountOperate();
// countOperate.setName("B");
//测试3
CountOperate countOperate=new CountOperate("B");
/**
* public Thread(Runnable target) {
* init(null, target, "Thread-" + nextThreadNum(), 0);
* }
*
* 如果未指定name:
* CountOperate继承了Thread,所以在初始化的时候回分配一个名称Thread-0。而t1则是第二个线程初始化,分配的名字是Thread-1
*/
Thread t1=new Thread(countOperate);
t1.setName("A");
t1.start();
}
}
class CountOperate extends Thread{
public CountOperate() {
System.out.println("CountOperate---begin");
System.out.println("Thread.currentThread().getName()="+Thread.currentThread().getName()); //Thread.currentThread().getName()指调用代码片段的线程名字
System.out.println("this.getName()="+this.getName()); //this指向自己;this.getName()指当前线程类的实例的名字;为设置name属性时,name属性会被默认设置
System.out.println("CountOperate---end");
}
public CountOperate(String name) {
this.setName(name);
System.out.println("CountOperate---begin");
System.out.println("Thread.currentThread().getName()="+Thread.currentThread().getName()); //调用代码片段的线程信息
System.out.println("this.getName()="+this.getName()); //当前线程类的名字
System.out.println("CountOperate---end");
}
@Override
public void run() {
System.out.println("run---begin");
System.out.println("Thread.currentThread().getName()="+Thread.currentThread().getName());
System.out.println("this.getName()="+this.getName());
System.out.println("run---end");
}
}