SunnyMorning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
一、仅使用synchronized来实现
通过创建两个线程,这两个线程共享object对象锁,当一个线程打印完一个数字后,会释放对象锁,另一个线程拿到对象锁,然后判断是否为偶数(奇数),满足条件则打印。
public class PrintNumTest1 {
    private static final Object obj = new Object();
    private static int count = 0;
    private static int num = 1000;
    public static void main(String[] args) {


        new Thread(new Runnable() {
            @Override
            public void run() {
                while (count <= num) {
                    synchronized (obj){
                        if((count&1) == 0) {
                            System.out.println(Thread.currentThread().getName()+ ++count);
                        }
                    }
                }
            }
        }, "奇数线程").start();


        new Thread(new Runnable() {
            @Override
            public void run() {
                while (count <= num) {
                    synchronized (obj){
                        if((count&1) == 1) {
                            System.out.println(++count);
                        }
                    }
                }
            }
        }, "偶数线程").start();
    }
}

 



二、使用notify()/wait()和synchronized实现

此种方式,写法简洁,让线程拿到对象锁后,立即打印数字,然后通过notify()释放锁,然后调用wait()方法使线程进入等待状态。另一个线程拿到锁以后,也立即打印数字,然后通过notify()释放锁,然后进入等待状态。知道打印完100以内的所有数字,两个线程都能正常停止运行。

public class PrintNumTest2 {
    private static final Object obj = new Object();
    private static int count = 0;


    public static void main(String[] args) {
        new Thread(new PrintNum(),"多线程A").start();
        new Thread(new PrintNum(),"多线程B").start();
    }

    static class PrintNum implements Runnable {
        @Override
        public void run() {
            while (count < 100) {
                synchronized (obj) {
                    System.out.println(Thread.currentThread().getName()+":"+ ++count);

                    obj.notify();
                    try {
                        obj.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }

                }
            }
        }
    }

}

 

 

 

posted on 2025-10-29 13:28  SunnyMorning  阅读(5)  评论(0)    收藏  举报