zoukankan      html  css  js  c++  java
  • 面试题:实现一个容器,提供两个方法,add,size;写两个线程,线程1添加10个元素到容器中,线程2实现监控元素的个数,当个数到5个时,线程2给出提示并结束

    主要思路是生产者消费者。当A线程打印到第5个时,让B线程的信号量加1;B线程开始执行并结束,结束前让A线程的信号量加1,A线程继续add

    import java.util.LinkedList;
    import java.util.List;
    import java.util.concurrent.Semaphore;
    
    public class TwoAddLearn {
        public static void main(String[] args) {
            Container container = new Container();
            Semaphore semaphoreA = new Semaphore(0);
            Semaphore semaphoreB = new Semaphore(0);
            ThreadA threadA = new ThreadA(container, semaphoreA, semaphoreB);
            ThreadB threadB = new ThreadB(container, semaphoreA, semaphoreB);
            threadA.start();
            threadB.start();
        }
    }
    
    class Container {
        private List<Integer> list = new LinkedList<>();
    
        public void add(Integer a) {
            list.add(a);
        }
    
        public int getSize() {
            return list.size();
        }
    }
    
    class ThreadA extends Thread {
        private Container container;
        private Semaphore semaphoreA;
        private Semaphore semaphoreB;
    
        ThreadA(Container container, Semaphore semaphoreA, Semaphore semaphoreB) {
            this.container = container;
            this.semaphoreA = semaphoreA;
            this.semaphoreB = semaphoreB;
        }
    
        @Override
        public void run() {
            super.run();
            for (int i = 1; i <= 10; i++) {
                if (container.getSize() == 5) {
                    semaphoreB.release();
                    try {
                        semaphoreA.acquire();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(i);
                container.add(i);
            }
        }
    }
    
    class ThreadB extends Thread {
        private Container container;
        private Semaphore semaphoreA;
        private Semaphore semaphoreB;
    
        ThreadB(Container container, Semaphore semaphoreA, Semaphore semaphoreB) {
            this.container = container;
            this.semaphoreA = semaphoreA;
            this.semaphoreB = semaphoreB;
        }
    
        @Override
        public void run() {
            super.run();
            try {
                semaphoreB.acquire();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("线程B结束");
            semaphoreA.release();
        }
    }

    执行结果

  • 相关阅读:
    log日志框架和LocationAwareLogger问题
    Eclipse 各种小图标的含义
    自定义log4j日志级别
    在Tomcat配置JNDI数据源的三种方式
    mybatis中"#"和"$"的区别
    Postman用法简介-Http请求模拟工具
    mustache模板技术(转)
    VS的编译选项
    Java Service Wrapper简介与使用
    还活着
  • 原文地址:https://www.cnblogs.com/billshen/p/13293515.html
Copyright © 2011-2022 走看看