Java多线程,循环打印“ABC”10次

作者: 被称为L的男人 | 来源:发表于2017-08-06 16:16 被阅读535次

    思路

    3个线程A,B,C分别打印三个字母,每个线程循环10次,首先同步,如果不满足打印条件,则调用wait()函数一直等待;之后打印字母,更新state,调用notifyAll(),进入下一次循环。

    代码

    package test;
    
    public class PrintABC {
        private static final int PRINT_A = 0;
        private static final int PRINT_B = 1;
        private static final int PRINT_C = 2;
        
        private static class MyThread extends Thread {
            int which; // 0:打印A;1:打印B;2:打印C
            static volatile int state; // 线程共有,判断所有的打印状态
            static final Object t = new Object();
            
            public MyThread(int which) {
                this.which = which;
            }
            
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    synchronized (t) {
                        while (state % 3 != which) {
                            try {
                                t.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        System.out.print(toABC(which)); // 执行到这里,表明满足条件,打印
                        state++;
                        t.notifyAll(); // 调用notifyAll方法
                    }
                }
            }
        }
        
        public static void main(String[] args) {
            new MyThread(PRINT_A).start();
            new MyThread(PRINT_B).start();
            new MyThread(PRINT_C).start();
        }
    
        private static char toABC(int which) {
            return (char) ('A' + which);
        }
    }
    

    相关文章

      网友评论

      • Vissioon:兄弟,你这个投到首页,是认真的吗?
        d693f48fa825:@名字什么的不重要 何为平常 何为新异 皆在施主一念之间
        ce4c10d6271a:@kingiis 是不在于深浅,但是你起码得告诉我你的这和平常的思路有啥区别啊
        d693f48fa825:知识不在与深浅,而是分享

      本文标题:Java多线程,循环打印“ABC”10次

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