在看多线程的时候,看到这个知识点,感觉需要验证一下。
一:线程自启动
1.程序
1 package com.jun.it.thread; 2 3 public class MyThread extends Thread { 4 MyThread(){ 5 System.out.println("----------"); 6 System.out.println("name:"+Thread.currentThread().getName()); 7 System.out.println("isActive:"+Thread.currentThread().isAlive()); 8 System.out.println("thisName:"+this.getName()); 9 System.out.println("thisIsActive:"+this.isAlive()); 10 System.out.println("----------"); 11 } 12 public void run(){ 13 System.out.println("======================="); 14 System.out.println("name:"+Thread.currentThread().getName()); 15 System.out.println("isActive:"+Thread.currentThread().isAlive()); 16 System.out.println("thisName:"+this.getName()); 17 System.out.println("thisIsActive:"+this.isAlive()); 18 System.out.println("======================="); 19 } 20 }
测试类:
1 package com.jun.it.thread; 2 3 4 public class RunMyThread { 5 public static void main(String[] args) { 6 test1(); 7 // test2(); 8 } 9 /** 10 * 测试一 11 */ 12 public static void test1(){ 13 MyThread myThread=new MyThread(); 14 myThread.setName("AA"); 15 myThread.start(); 16 } 17 18 /** 19 * 测试二 20 */ 21 public static void test2(){ 22 MyThread myThread=new MyThread(); 23 Thread thread=new Thread(myThread); 24 thread.setName("BB"); 25 thread.start(); 26 } 27 }
2.效果:
3.总结
Thread.currentThread():表示当前的代码正在被谁调用。
this:只能是当前的线程,在程序中,代表是myThread。
PS:
至于thread-0:每次新new的时候,在构造函数中,会定义默认的线程名。
二:线程被作为参数传入Thread
1.程序
启动测试2
2.效果
3.总结
根据上文的说法,this代表myThread,则说明,线程没有开启。
在这个示例中,外部线程在start后启动,实际上调用的是内部线程的run方法开启的。
Thread.currentThread()与this指向了不同的线程对象,Thread.currentThread()指向的是外部的线程,表示当前方法被外部线程thread调用;this指向内部线程myThread。