weixin_42401461 2010-10-18 10:53
浏览 295
已采纳

一道有趣的字符串笔试题 以及队列问题笔试题

  1. 请完成函数,该函数输入一个纯英文字符串,请打印出该字符串中每个字符(区分大小写)出现的次数,并按照出现的次数从大到小排列,如输入“asisaB”,则打印出a=2,s=2,i=1,B=1。 注:要求不能使用如Map,List等集合类。

2.使用Java实现阻塞队列BlockQueue,请插入数据调用Offer,如果已满则等待。获取数据调用take,如果队列为空,则等待。请完成该类

请高人写出程序代码 加有些详细注解更佳 谢谢!!!!!!!!!!!!!!!!!

  • 写回答

1条回答 默认 最新

  • weixin_42361038 2010-10-19 10:41
    关注

    第二题:

    [code="java"]
    public class BlockingQ {
    //增加的时候加锁用
    private Object notEmpty = new Object();
    //判断容量的时候加锁用
    private Object notFull = new Object();
    private Queue linkedList = new LinkedList();
    private int maxLength = 10;

    public BlockingQ(int maxLength) {
        this.maxLength = maxLength;
    }
    
    
    /**
     * 
    * 如果队列为空,则等待
    * @return
    * @throws InterruptedException
     */
    public Object take() throws InterruptedException {
        synchronized (notEmpty) {
            if (linkedList.size() == 0) {
                notEmpty.wait();
            }
            synchronized (notFull) {
                if (linkedList.size() == maxLength) {
                    notFull.notifyAll();
                }
                return linkedList.poll();
            }
        }
    }
    
    /**
     * 
    * 如果已满则等待
    * @param object
    * @throws InterruptedException
     */
    public void offer(Object object) throws InterruptedException {
        synchronized (notEmpty) {
            if (linkedList.size() == 0) {
                notEmpty.notifyAll();
            }
            synchronized (notFull) {
                if (linkedList.size() == maxLength) {
                    notFull.wait();
                }
                linkedList.add(object);
            }
        }
    }
    

    }[/code]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?