线程对象的获取、线程名字的获取及修改
1 package XianChengFenXi; 2 /* 3 * 1.如何获取当前线程对象? 4 * 静态方法:static Thread currentThread(); 5 * Thread tt=Thread.currentThread();返回值tt就是当前线程 6 * 2.获取线程对象的名字 7 * 3.修改线程对象的名字 8 */ 9 10 public class ThreadTest5 { 11 12 public static void main(String[] args){ 13 14 //返回当前线程,这个tt就是当前线程对象 15 //这个代码出现在main()方法中,所以当前线程就是主线程 16 Thread tt=Thread.currentThread(); 17 System.out.println(tt.getName());//主线程的名字就叫main 18 19 20 MyThread2 t1=new MyThread2(); 21 MyThread2 t2=new MyThread2(); 22 23 //设置线程名字 24 t1.setName("我是t1"); 25 t2.setName("我是t2"); 26 27 //获取线程名字 28 t1.getName(); 29 30 //启动线程 31 t1.start(); 32 t2.start(); 33 for(int i=0;i<10;i++){ 34 System.out.println("主线程++++++++++"+tt.getName()+"++++++++"+i); 35 } 36 37 38 } 39 40 } 41 42 class MyThread2 extends Thread{ 43 public void run(){ 44 for(int i=0;i<10;i++){ 45 Thread tt=Thread.currentThread(); 46 System.out.println("分支线程-----"+tt.getName()+"------"+i); 47 } 48 } 49 }
运行结果:


浙公网安备 33010602011771号