使用 wait notify 实现一个队列,队列有2个方法,add 和 get 。add方法往队列中添加元素,get方法往队列中获得元素。队列必须是线程安全的。如果get执行时,队列为空,线程必须阻塞

使用 wait notify 实现一个队列,队列有2个方法,add 和 get 。add方法往队列中添加元素,get方法往队列中获得元素。队列必须是线程安全的。如果get执行时,队列为空,线程必须阻塞等待,直到有队列有数据。如果add时,队列已经满,则add线程要等待,直到队列有空闲空间。使他工作在多线程的环境下,证明,它的工作是正确的。给出程序和运行的截图。

//关键点: wait() notify() 锁住同一资源
private static final int maxLenth = 10;

    static Object lock = new Object();

    private Queue<Integer> list = new LinkedList<Integer>();

    private Integer i = 0;

    public void add() throws Exception{
        synchronized (lock) {
            Thread.sleep(1000);
            if(list.size()==maxLenth){
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    System.out.println("队列满了当前list长度:"+list.size());
                    lock.notifyAll();
                }
            }
            list.add(++i);
            System.out.println("加入i值:"+i);
            lock.notifyAll();
        }
    }

    public Integer get() throws Exception{
        synchronized (lock) {
            Thread.sleep(1000);
            if(list.size()==0){
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    System.out.println("队列空了当前list长度:"+list.size());
                    lock.notifyAll();
                }
                return null;
            }
            Integer poll = list.poll();
            System.out.println("移除i值:"+poll);
            lock.notifyAll();
            return poll;
        }
    }



    public static void main(String[] args) throws Exception {
        Task2 t = new Task2();

        for (int i = 0; i < 5; i++) {
            new Thread(){
                public void run() {
                    while(true){
                        try {
                            t.add();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                };
            }.start();
        }

        for (int i = 0; i < 5; i++) {
            new Thread(){
                public void run() {
                    while(true){
                        try {
                            t.get();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                };
            }.start();
        }

    }
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值