Java不使用锁让两个线程顺序打印1~100

两个线程,其中一个打印奇数,另一个打印偶数,打印的结果是按照顺序1~100,不使用锁。

import java.util.concurrent.atomic.AtomicInteger;

public class PrintOneToOneHundred {

    private static int num = 1;

    private static final AtomicInteger x = new AtomicInteger(0);

    // 打印奇数
    private static class PrintOdd extends Thread {
        @Override
        public void run() {
            while (true) {
                while (x.compareAndSet(0, 2)) {
                    int t = num++;
                    System.out.println(t);
                    x.compareAndSet(2, 1);
                    if (t == 99) return;
                }
            }
        }
    }

    // 打印偶数
    private static class PrintEven extends Thread {
        @Override
        public void run() {
            while (true) {
                while (x.compareAndSet(1, 3)) {
                    int t = num++;
                    System.out.println(t);
                    x.compareAndSet(3, 0);
                    if (t == 100) return;
                }
            }
        }
    }

    public static void main(String[] args) {
        new PrintOdd().start();
        new PrintEven().start();
    }

}
posted @ 2020-09-03 10:05  SanjiApollo  阅读(435)  评论(0编辑  收藏  举报