Java#双线程打印奇偶数

该博客展示了如何使用Java实现多线程同步,通过`synchronized`关键字和`wait/notifyAll`方法,确保两个线程交替打印奇偶数,从0到100。示例中创建了两个线程`t1`和`t2`,分别负责打印奇数和偶数。

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

public class PrintNum {
    
    public static Integer number=0  ;
    static final Object o=new Object() ;

    public static void main(String[] args) {
       Thread t1=new Thread(new Runnable() {
   
           @Override
           public void run() {
               while(number<100){
                   synchronized(o){

                       if((number&1)==1){
                           try {
                               o.wait();
                           } catch (InterruptedException e) {
                               e.printStackTrace();
                           }
                       }
                       System.out.println(Thread.currentThread().getName() + "-->" + number++);
                       o.notifyAll();
                   }
               }
           }
       }) ;

        Thread t2=new Thread(new Runnable() {
          
            @Override
            public void run() {
                while (number<100){
                    synchronized (o){

                        if((number&1)==0){
                            try {
                                o.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        System.out.println(Thread.currentThread().getName() + "-->" + number++) ;
                        o.notifyAll();
                    }
                }
            }

        }) ;

        t1.setName("t1");
        t2.setName("t2");
        t1.start();
       /* try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
        t2.start();

    }
}
D:\Java\jdk\bin\java.exe 
t1-->0
t2-->1
t1-->2
t2-->3
t1-->4
t2-->5
t1-->6
t2-->7
t1-->8
t2-->9
t1-->10
t2-->11
t1-->12
t2-->13
t1-->14
t2-->15
t1-->16
t2-->17
t1-->18
t2-->19
t1-->20
t2-->21
t1-->22

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值