两个线程交替打印0-100的奇偶数

题目:两个线程,其中一个线程打印奇数,另一个打印偶数,交替输出0-100

方法1:自旋判断

开启两个线程,每个线程自旋判断当前值是奇数/偶数,然后打印

public class Test {

    volatile static int i = 0;

    public static void main(String[] args) {
        Thread thread1 = new Thread(() -> {
            while (i <= 100) {
                if (i % 2 == 0) {
                    System.out.println(i + "===偶数");
                    i++;
                }
            }
        });

        Thread thread2 = new Thread(() -> {
            while (i <= 100) {
                if (i % 2 != 0) {
                    System.out.println(i + "===奇数");
                    i++;
                }
            }
        });

        thread1.start();
        Thread.sleep(1);//确保偶数线程先获取到锁
        thread2.start();
    }
}

为什么变量要用volatile关键字修饰,留个坑后续补,着急的读者可以搜索关键字“i++是线程安全么?”来了解。

方法2:交替获取锁

public class Test {

    static volatile int i = 0;

    static Object lock = new Object();

    public static void main(String[] args) throws InterruptedException {

        Thread thread1 = new Thread(() -> {
            while (i <= 100) {
                synchronized (lock) {
                    lock.notify();
                    System.out.println(i + "===偶数");
                    i++;
                    try {
                        //如果大于100则不再进行线程等待,否则程序永远无法结束
                        if (i <= 100) {
                            lock.wait();
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        Thread thread2 = new Thread(() -> {
            while (i < 100) {
                synchronized (lock) {
                    lock.notify();
                    System.out.println(i + "===奇数");
                    i++;
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();

                    }
                }
            }
        });

        thread1.start();
        thread1.setName("ThreadA");
        Thread.sleep(1);//确保偶数线程先获取到锁
        thread2.start();
        thread2.setName("ThreadB");
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容