工作

工作,new线程的几种写法:

 1 public class DemoClass4Run {
 2     public static void main(String[] args) {
 3         //TODO 线程 - 工作
 4 
 5         /*
 6         * 1. 这样t3 t4 多个类,失去了面向对象的意义
 7         * */
 8         /*MyThread3 t3 = new MyThread3();
 9         t3.start();
10 
11         MyThread4 t4 = new MyThread4();
12         t4.start();
13 
14         System.out.println("main线程执行");*/
15 
16         /*
17         * 2. 1的问题,可以这样解决
18         * */
19         /*MyThread5 t51 = new MyThread5("1001");
20         MyThread5 t52 = new MyThread5("1002");
21         t51.start();
22         t52.start();
23         System.out.println("main 线程执行");*/
24 
25         /*
26         * 3. 更简单的写法(常用)
27         *    构建线程对象时,可以只把逻辑传递给线程对象,不用自己在写类
28         *    传递逻辑是,需要遵循规则写法:() -> { 逻辑 }
29         * */
30         /*Thread t6 = new Thread(() -> {
31             System.out.println("t6 线程执行");
32         });
33         t6.start();
34         System.out.println("main 线程执行");*/
35 
36         /*
37         * 4. 更简单的写法2(常用)
38         *  构建线程对象时,可以传递实现了Runnable接口的类的对象(一般使用匿名类),
39         * */
40         Thread t7 = new Thread(new Runnable() {
41             @Override
42             public void run() {
43                 System.out.println("t7 线程执行");
44             }
45         });
46         t7.start();
47         System.out.println("main 线程执行");
48     }
49 }
50 
51 class MyThread3 extends Thread {
52      public void run() {
53          System.out.println("t3 线程执行完成");
54      }
55 }
56 
57 class MyThread4 extends Thread {
58     public void run() {
59         System.out.println("t4 线程执行完成");
60     }
61 }
62 
63 class MyThread5 extends Thread {
64      private String threadName;
65      public MyThread5(String threadName) {
66          this.threadName = threadName;
67      }
68      public void run() {
69          System.out.println(threadName + " 线程执行完成");
70      }
71 }

 

posted @ 2025-10-23 10:50  字节虫  阅读(32)  评论(0)    收藏  举报