创建线程的方式一:实现Runnable接口

 1 package day2_4;
 2 
 3 /**
 4  * 创建线程的方式二:实现Runnable接口
 5  * 1.实现Runnable接口,并实现其抽象方法run()
 6  * 2.创建这个实现类的对象
 7  * 3.将这个是实现类对象作为参数传递到Thread类的构造器中,并创建Thread类的对象
 8  * 4.调用Thread类的start()
 9  *
10  *
11  *比较创建线程的两种方式
12  * 开发中,优先选择:实现Runnable接口的方式
13  * 原因:1.实现的方式没有类的单继承的局限性
14  *      2.实现的方式更适合处理多个线程共享数据的情况
15  *
16  * 联系:public class Thread implements Runnable
17  * 相同点:两种方式都需要重写run(),将线程要执行的逻辑声明在run()中
18  *        目前两种方式,要想启动线程,都是调用Thread类的start()
19  *
20  *
21  *
22  * @Author Tianhao
23  * @create 2021-02-04-10:59
24  */
25 
26 
27 
28 
29 class Mthread implements Runnable {
30 
31     @Override
32     public void run() {
33         for (int i = 0; i < 100; i++) {
34             if (i % 2 == 0) {
35                 System.out.println(Thread.currentThread().getName() + ":" + i);
36             }
37         }
38     }
39 }
40 
41 
42 public class ThreadTest2 {
43     public static void main(String[] args) {
44         Mthread mthread = new Mthread();
45         Thread t = new Thread(mthread);
46         t.setName("线程一");
47         t.start();  //底层是调用Thread类中Runnab类型的成员变量target的run()
48 
49         //再启动一个线程
50         Thread t2 = new Thread(mthread);
51         t2.setName("线程二");
52         t2.start();
53 
54         Thread.currentThread().setName("main线程");
55         for (int i = 0; i < 100; i++) {
56             if (i % 2 == 0) {
57                 if (i == 20) {
58                     //yield() 释放当前cup的执行权
59                     Thread.currentThread().yield();
60                 }
61                 System.out.println(Thread.currentThread().getName() + ":" + i);
62             }
63         }
64     }
65 }
原文地址:https://www.cnblogs.com/zui-ai-java/p/14377366.html