多线程的创建

* 多线程的创建,方式一:继承于Thread类
* 1.创建一个继承于Thread类的子类
* 2.重写Thread类的run()-->将此线程执行的操作声明在run()中
* 3.创建Thread类的子类的对象
* 4.通过此对象调用Thread类的start():①启动当前线程;②调用当前线程的run()
* 创建多线程的方式二:实现Runnable接口
* 1.创建一个实现了Runnable接口的类
* 2.实现类去实现Runnable中的抽象方法:run()
* 3.创建实现类的对象
* 4.将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象
* 5.通过Thread类的对象调用start()
* 比较创建线程的两种方式:
* 1.开发中:优先选择:实现Runnable接口的方式
* 原因:1.实现的方式没有类的单继承性的局限性
* 2.实现的方式更适合来处理多个线程共享数据的情况。
*
* 联系:public class Thread implements Runnable(Thread类也实现了Runnable接口)
*相同点:两种方式都需要重写run(),将线程要执行的逻辑声明再run()中
*  
 1 package com.atfu.java01;
 2 
 3 /**
 4  * 多线程的创建,方式一:继承于Thread类
 5  * 1.创建一个继承于Thread类的子类
 6  * 2.重写Thread类的run()-->将此线程执行的操作声明在run()中
 7  * 3.创建Thread类的子类的对象
 8  * 4.通过此对象调用Thread类的start():①启动当前线程;②调用当前线程的run()
 9  *
10  * 例子:遍历100以内所有的偶数
11  *
12  * @author fu jingchao
13  * @creat 2021/10/13-21:16
14  */
15 class MyThread extends Thread{
16     @Override
17     public void run() {
18         for (int i = 0; i < 10000; i++) {
19             if(i%2 ==0){
20                 System.out.println(i);
21             }
22         }
23     }
24 }
25 
26 
27 public class ThreadTest {
28     public static void main(String[] args) {
29         MyThread m1 = new MyThread();
30         //我们不能直接调用run()的方式启动线程
31 //        m1.run();
32 
33         m1.start();
34         //再启动一个线程,遍历100以内的偶数,不可以还让已经start()的线程去执行,否则会报IllegalThreadStateException
35 //        m1.start();
36         //需要重新创建一个线程的对象
37         MyThread m2 = new MyThread();
38         m2.start();
39 
40         for (int i = 0; i < 10000; i++) {
41             if(i%2 ==0){
42                 System.out.println(i+"主线程");
43             }
44         }
45     }
46 }
 
 1 package com.atfu.java01;
 2 
 3 /**
 4  * 创建多线程的方式二:实现Runnable接口
 5  * 1.创建一个实现了Runnable接口的类
 6  * 2.实现类去实现Runnable中的抽象方法:run()
 7  * 3.创建实现类的对象
 8  * 4.将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象
 9  * 5.通过Thread类的对象调用start()
10  *
11  *
12  * @author fu jingchao
13  * @creat 2021/10/15-16:43
14  */
15 
16 class MThread implements Runnable{
17 
18     @Override
19     public void run() {
20         for (int i = 0; i < 100; i++) {
21             if( i % 2 == 0){
22                 System.out.println(Thread.currentThread().getName()+ ":" +i);
23             }
24         }
25     }
26 }
27 
28 
29 public class ThreadTest1 {
30     public static void main(String[] args) {
31         MThread mThread = new MThread();
32         Thread t1 = new Thread(mThread);
33         t1.setName("线程1");
34         t1.start();
35 
36         //再启动一个线程,遍历100以内的偶数
37         Thread t2 = new Thread(mThread);
38         t2.setName("线程2");
39         t2.start();
40     }
41 }

 

 
posted @ 2021-10-15 22:27  橘猫的夏天  阅读(70)  评论(0编辑  收藏  举报