1. 直接用CAS中的AtomicInteger

package concurency.chapter13;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @auther draymonder
 */
public class PrintOddAndEven {
    public static volatile boolean flag = false;

    public static AtomicInteger num = new AtomicInteger();

    public static void main(String[] args) {
        new Thread(()->{
            while(num.get() < 100) {
                if(flag) {
                    System.out.println(Thread.currentThread() +  " " + num.getAndIncrement());
                    flag = false;
                }
            }

        }, "奇数").start();

        new Thread(()->{
            while(num.get() < 100) {
                if(!flag) {
                    System.out.println(Thread.currentThread() + " " + num.getAndIncrement());
                    flag = true;
                }
            }
        }, "偶数").start();
    }
}

第二种 带锁版

注意 奇数是 < 100 偶数是<=100

package concurency.chapter13;

/**
 * @auther draymonder
 */
public class Print2 {
    // flag = 0 now odd   flag = 1 now even
    public static volatile boolean flag = true;
    public static final Object lock = new Object();
    public static volatile int num = 0;

    public static void main(String[] args) {
        new Thread(()->{
            while(num < 100) {
                synchronized (lock) {
                    if (flag) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println(Thread.currentThread() + " " + num++);
                    flag = true;
                    lock.notifyAll();
                }
            }
        },"奇数").start();
        new Thread(()->{
            while(num <= 100) {
                synchronized (lock) {
                    if (!flag) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println(Thread.currentThread() + " " + num++);
                    flag = false;
                    lock.notifyAll();
                }
            }
        },"偶数").start();
    }
}

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-06-24
  • 2022-12-23
  • 2021-10-31
  • 2022-12-23
  • 2022-12-23
  • 2021-07-10
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-29
  • 2022-12-23
相关资源
相似解决方案