Bootstrap

两个线程交替打印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");
    }
}
;