• 两个线程交替打印1-100


    public class Solution2 {
        private static final Object lock = new Object();  //表示对象锁
    
        private volatile int index = 1;           //表示要输出的数字
    
        private volatile boolean aHasPrint = false;      //记录A是否被打印过
    
        class A implements Runnable {
            @Override
            public void run() {
                for (int i = 0; i < 50; i++) {
                    synchronized (lock) {
                        while (aHasPrint) {              //如果A已经打印过就进行阻塞
                            try {
                                lock.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        System.out.println("A:" + index);    //A没有打印过则输出A的值
                        index++;                   //输出的值增加1
                        aHasPrint = true;             //表示A已经打印过
                        lock.notifyAll();            //唤醒其它线程执行
                    }
                }
            }
        }
    
        class B implements Runnable {
            @Override
            public void run() {
                for (int i = 0; i < 50; i++) {
                    synchronized (lock) {
                        while (!aHasPrint) {               //如果A没有打印过则阻塞
                            try {
                                lock.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        System.out.println("B:" + index);  //输出B的值
                        index++;                 //计数加一
                        aHasPrint = false;          //B打印完了说明新的一轮开始了,将标识为计为A没有打印过
                        lock.notifyAll();          //唤醒阻塞线程
                    }
                }
            }
        }
    
    
        public static void main(String[] args) {
            Solution2 solution2 = new Solution2();
            Thread threadA = new Thread(solution2.new A());
            Thread threadB = new Thread(solution2.new B());
            threadA.start();
            threadB.start();
        }
    }

     相关代码 https://github.com/LiWangCai/blogRelated 可自行获取

  • 相关阅读:
    axios 修改头部请求数据格式的方法
    基于VUE的可以滚动的横向时间轴
    25.客户端多线程分组模拟高频并发数据
    24.原子操作
    23.线程锁的使用
    22.线程自解锁
    21.多线程-锁与临界区域
    20.多线程-基本代码
    19.添加高精度计时器测量处理能力
    18.windows使用select突破64个socket
  • 原文地址:https://www.cnblogs.com/liwangcai/p/10741644.html
Copyright © 2020-2023  润新知