public class ProducerAndConsumer {
    private static int cp = 0;
    private static int allNum = 20;
    static Object obj = new Object();

    public static void main(String[] a){
        Producer p = new Producer();
        Consumer c = new Consumer();
        p.start();
        c.start();
    }

    private static class Producer extends Thread{
        @Override
        public void run() {
            while (true){
                synchronized (obj){
                    try {
                        while(cp>=allNum){
                            System.out.println("满了!!!!!!!!!!!!!");
                            obj.wait();
                        }
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
                    cp++;
                    System.out.println("生产--仓库:"+cp);
                    obj.notifyAll();
                }
            }
        }
    }
    
    private static class Consumer extends Thread{
        @Override
        public void run() {
            while (true){
                synchronized (obj) {
                    try {
                        while (cp==0){
                            System.out.println("空了。。。。。。");
                            obj.wait();
                        }
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
                    cp--;
                    System.out.println("消费--仓库:"+cp);
                    obj.notifyAll();
                }
            }
        }
    }
}

等待超时模式  应用-数据库连接池

事例关键代码

/*容器,存放连接*/
private static LinkedList<Connection> pool = new LinkedList<Connection>();

//释放链接,通知其他等待连接的线程
public void releaseConnection(Connection connection){
    if(connection != null){
        synchronized(pool){
            pool.addLast(connection);
            pool.notifyAll();
        }
    }
}

//获取链接,在mills内无法获取则返回null
public Connection fetchConnection(long mills) throws InterruptedException{
    synchronized(pool){
        if(mills<0){
            while(pool.isEmpty()){
                pool.wait();
            }
            return pool.removeFirst();
        }else{
            long future = System.currentTimeMillis()+mills;//获取超时时刻
            long remaining = mills;//等待时长
            while(pool.isEmpty() && remaining>0){//当池空且等待时长大于0,继续等待
                pool.wait(remaining);//休眠remaining时间
                //中途每次被唤醒的话,等待时长要重新计算
                remaining = future - System.currentTimeMillis();
            }
            Connection connection = null;
            if(!pool.isEmpty()){
                connection = pool.removeFirst()
            }
            return connection ;
        }
    }
}

 

最后修改于 2019-08-21 17:14:57
如果觉得我的文章对你有用,请随意赞赏
扫一扫支付
上一篇