两个线程交替打印1-99

参考https://github.com/crossoverJie/JCSprout/blob/master/src/main/java/com/crossoverjie/actual/TwoThread.java从线程方面实现交替打印。

public class Test {
    volatile boolean isEven = false;
    @org.junit.Test
    public void testfda() throws InterruptedException {
        Thread a = new Thread(new OddThread(), "thread-1");
        Thread b = new Thread(new EvenThread(), "thread-2");
        a.start();
        b.start();
        Thread.sleep(5000);
    }

    

    class OddThread implements Runnable {

        @Override
        public void run() {
            int i = 1;
            while (i < 100) {
                if (!isEven) {
                    System.err.println(Thread.currentThread().getName() + ":" + i);
                    i = i + 2;
                    isEven = true;
                }
            }
        }
    }

    class EvenThread implements Runnable {

        @Override
        public void run() {
            int i = 2;
            while (i < 100) {
                if (isEven) {
                    System.err.println(Thread.currentThread().getName() + ":" + i);
                    i = i + 2;
                    isEven = false;

                }
            }
        }
    }
}
当你准备好了,机会来临的时候,你才能抓住
原文地址:https://www.cnblogs.com/studentytj/p/10428584.html