给线程起名

//  用 API 给线程起名
1
public class MyThreadApi extends Thread { 2 @Override 3 public void run(){ 4 for (int i = 0; i < 5; i++) { 5 System.out.println(Thread.currentThread() + "子线程:" + i); 6 } 7 } 8 }
 1  1 public static void main(String[] args) {
 2  2         Thread t1 = new MyThreadApi();
 3  3         t1.setName("一号");
 4  4         t1.start();
 5  5         System.out.println(t1.getName());
 6  6 
 7  7         t2.setName("二号");
 8  8         t2.start();
 9  9         System.out.println(t2.getName());
10 10 
11 11         //  哪个线程执行它,就得到那个线程对象
12 12         Thread m = Thread.currentThread();
13 13         System.out.println(m.getName());
14 14 
15 15         for (int i = 0; i < 5; i++) {
16 16             System.out.println("主线程:" + i);
17 17         }
18 18     }
 1 //    用构造器给线程起名
 2 public class MyThreadApi extends Thread {
 3     public MyThreadApi() {
 4     }
 5 
 6     public MyThreadApi(String name) {
 7         //  为当前线程起名,给父类的有参构造器初始化名称
 8         super(name);
 9     }
10 
11     @Override
12     public void run(){
13         for (int i = 0; i < 5; i++) {
14             System.out.println(Thread.currentThread() + "子线程:" + i);
15         }
16     }
17 }
18 
19     public static void main(String[] args) {
20         Thread t1 = new MyThreadApi("1号");
21         t1.start();
22         System.out.println(t1.getName());
23 
24         Thread t2 = new MyThreadApi("2号");
25         t2.start();
26         System.out.println(t2.getName());
27 
28         //  哪个线程执行它,就得到那个线程对象
29         Thread m = Thread.currentThread();
30         m.setName("main主线程");
31 
32         for (int i = 0; i < 5; i++) {
33             System.out.println(m.getName() + i);
34         }
35     }

 

posted @ 2024-01-29 20:33  小※兽  阅读(11)  评论(0编辑  收藏  举报