多线程实现奇偶数的依次输出

话不多说直接上代码:

 1 package 多线程;
 2 
 3 public class Test13_多线程实现奇偶数依次输出 {
 4     public static void main(String[] args) {
 5 
 6         //创建共享数据对象
 7         Num num = new Num(1);
 8 
 9         //创建线程对象,两个线程都共享Num数据
10         Thread t1 = new Thread(new PrintOdd(num));
11         t1.setName("奇数");
12         Thread t2 = new Thread(new PrintEven(num));
13         t2.setName("偶数");
14 
15         //启动线程、
16         t1.start();
17         t2.start();
18 
19     }
20 }
21 
22 
23 
24 //共享数据
25 class Num{
26     int count;//共享
27     public Num(int count){
28         this.count = count;
29     }
30     //对外提供打印奇数的方法
31     public void printOdd() throws InterruptedException {
32         synchronized(this){
33             System.out.println(Thread.currentThread().getName()+"--->"+count++);
34             Thread.sleep(1000);
35             this.notifyAll();
36             this.wait();
37         }
38     }
39     //对外提供打印偶数的方法
40     public void printEven() throws InterruptedException {
41         synchronized(this){
42             System.out.println(Thread.currentThread().getName()+"--->"+count++);
43             Thread.sleep(1000);
44             this.notifyAll();
45             this.wait();
46         }
47     }
48 
49 }
50 
51 
52 //线程1
53 class PrintOdd implements Runnable{
54     Num num;
55     //构造
56     public PrintOdd(Num num){
57         this.num = num;
58     }
59 
60     //run方法打印奇数
61     public void run() {
62         while(true){
63             try {
64                 num.printOdd();
65             } catch (InterruptedException e) {
66                 e.printStackTrace();
67             }
68         }
69     }
70 }
71 //线程2
72 class PrintEven implements  Runnable{
73     Num num;
74     public PrintEven(Num num){
75         this.num = num;
76     }
77     //run方法打印偶数
78     public void run() {
79         while(true){
80             try {
81                 num.printEven();
82             } catch (InterruptedException e) {
83                 e.printStackTrace();
84             }
85         }
86     }
87 }
点击这里

运行结果:

 

 
posted @ 2020-08-14 21:23  Java小白的搬砖路  阅读(318)  评论(0编辑  收藏  举报