美文网首页
多线程顺序打印(写入集合)

多线程顺序打印(写入集合)

作者: 三分归元币 | 来源:发表于2020-02-21 10:16 被阅读0次

    使用CAS思想

    这种方式就是会使得线程空跑,不会有线程的启动挂起

    class TheadPrint implements Runnable{
    
        private AtomicInteger letter;
    
        private final int log;
    
        private final char print;
    
        public TheadPrint(AtomicInteger letter, int log, char print) {
            this.letter = letter;
            this.log = log;
            this.print = print;
        }
    
        @Override
        public void run() {
            int i=0;
            while (i<100){
                if(letter.get() % 2 == log){
                    System.out.print(print);
                    letter.incrementAndGet();
                    i++;
                }
            }
        }
    }
    
    image.png

    使用lock的方式

    这种方式就是需要Park和UnPark线程

    class TheadPrint1 implements Runnable{
        @Override
        public void run() {
            while (true){
                Application.lock.lock();
                if(Application.state % 2 == 0){
                    System.out.println("A");
                    Application.state ++;
                }
                Application.lock.unlock();
            }
    
        }
    }
    class TheadPrint2 implements Runnable{
        @Override
        public void run() {
            while (true){
                Application.lock.lock();
                if(Application.state % 2 == 1){
                    System.out.println("B");
                    Application.state ++;
                }
                Application.lock.unlock();
            }
        }
    }
    
    image.png

    改进方式

    class PrintThread implements Runnable{
        private Lock lock;
        private AtomicInteger signal ;
        private char[] printArray;
        public PrintThread(Lock lock ,AtomicInteger signal,char[] printArray) {
            this.lock = lock;
            this.signal = signal;
            this.printArray = printArray;
        }
    
        @Override
        public void run() {
            for(int i=0;i<100;i++){
                try {
                    lock.lock();
                    if(printArray != null && printArray.length > 0){
                        System.out.println(printArray[Math.abs(signal.get() % printArray.length)]);
                    }
                    signal.incrementAndGet();
                }finally {
                    lock.unlock();
                }
            }
        }
    }
    

    总结

    这两种方式都要涉及到公共资源的修改,必须有公共变量,一种是乐观模式一种是悲观模式

    相关文章

      网友评论

          本文标题:多线程顺序打印(写入集合)

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