交叉打印奇数偶数

博客分享了一个名为交叉打印的题目,题目内容转载自https://www.cnblogs.com/JingM/p/10956126.html 。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:交叉打印

 

 1 public class OddThread{
 2     private int i=1;
 3     public synchronized void printOdd() {
 4         while(i<100) {
 5             if(i%2==0) {
 6                 try {
 7                     this.wait();
 8                 } catch (InterruptedException e) {
 9                     e.printStackTrace();
10                 }
11             }
12             System.out.println(i);
13             i++;
14             this.notify();
15         }
16     }
17 
18   public synchronized void printEvent() {
19       while(i<100) {
20           if(i%2==1) {
21               try {
22                 this.wait();
23             } catch (InterruptedException e) {
24                 e.printStackTrace();
25             }
26           }
27           System.out.println(i);
28           i++;
29           this.notify();
30       }
31   }
32   
33   
34   public static void main(String[] args) {
35     OddThread o = new OddThread();
36     new Thread(new Runnable() {
37         public void run() {
38             o.printOdd();
39             
40         }
41     }).start();
42     
43     new Thread(new Runnable() {
44         public void run() {
45              o.printEvent();
46             
47         }
48     }).start();
49 }
50 }

 

转载于:https://www.cnblogs.com/JingM/p/10956126.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值