Java 多线程------创建多线程的方式二:实现 Runnable接口 + 比较创建线程的两种方式:

 1 package com.bytezero.threadexer;
 2 
 3 /**
 4  *
 5  * 创建多线程的方式二:实现 Runnable接口
 6  * 1.创建一个实现了Runnable接口类
 7  * 2.实现类去实现Runnable中的抽象方法:run()
 8  * 3.创建实现类的对象
 9  * 4.将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象
10  * 5.通过Thread类的对象调用start()
11  *
12  * 比较创建线程的两种方式:
13  *  开发中 优先选择实现Runnable接口的方式
14  *  原因:1.实现的方式没有类的单继承的局限性
15  *       2.实现的方式更适合来处理多个线程有共享数据的情况
16  *
17  *   联系:public class Thread implements Runnable
18  *   相同点:两种方式都需要重写 run(),将线程要执行的逻辑声明在run()中
19  *
20  *
21  *
22  * @author Bytezero1·zhenglei!    Email:420498246@qq.com
23  * create  2021-10-15 17:21
24  */
25 
26 //1.创建一个实现了Runnable接口类
27 class MThread implements Runnable {
28  //2.实现类去实现Runnable中的抽象方法:run()
29 
30     @Override
31     public void run() {
32         for (int i = 0; i < 100; i++) {
33             if( i % 2==0){
34                 System.out.println(Thread.currentThread().getName()+":"+i);
35             }
36         }
37     }
38 }
39 
40 public class RunnableTest {
41     public static void main(String[] args) {
42         //3.创建实现类的对象
43         MThread mThread = new MThread();
44 
45        // 4.将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象
46         Thread t1 = new Thread(mThread);
47 
48 
49        //  * 5.通过Thread类的对象调用start():①启动线程 ②调用当前线程的run()-->调用了 R
50      //Runnable类型的target的run()
51         t1.setName("线程一");
52        t1.start();
53 
54        //再启动线程1遍历100以内的偶数
55         Thread t2 = new Thread(mThread);
56         t2.setName("线程二");
57         t2.start();
58     }
59 }

 

 ...............

posted on 2021-10-15 19:07  Bytezero!  阅读(43)  评论(0编辑  收藏  举报