美文网首页Java多线程
两个线程交替打印1-99

两个线程交替打印1-99

作者: ReentrantSucc | 来源:发表于2018-12-19 11:59 被阅读15次

    参考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;
    
                    }
                }
            }
        }
    }
    

    相关文章

      网友评论

        本文标题:两个线程交替打印1-99

        本文链接:https://www.haomeiwen.com/subject/yrpdkqtx.html