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

 


话不多说直接上代码:

复制代码
 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 @   Java小白的搬砖路  阅读(327)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话

喜欢请打赏

扫描二维码打赏

支付宝打赏

点击右上角即可分享
微信分享提示