zoukankan      html  css  js  c++  java
  • 线程 ---- 锁(生产者、消费者)

    Java经典面试题 -----  生产者消费者

    /**
     * 生产者 消费者问题
     * 解释 : wait notify 方法
     * sleep 与 wait的区别
     * 线程锁机制
     */
    public class ProducerConsumer {
        public static void main(String[] args) {
            SyncStack ss = new SyncStack();
            Producer p = new Producer(ss);
            Consumer c = new Consumer(ss);
            
            new Thread(p).start();
            new Thread(c).start();
        }
    }
    
    class MT{
        int id ;
        MT(int id){
            this.id = id;
        }
        
        public String toString(){
            return "MT:" + id;
        }
    }
    
    class SyncStack {
        int index = 0 ;
        MT[] mts = new MT[6];
        
        public synchronized void push (MT mt){
            if(index == mts.length){
                try {
                    this.wait();
                }catch(InterruptedException ex){
                    ex.printStackTrace();
                }
            }
            this.notify();
            mts[index] = mt;
            index ++;
        }
        
        public synchronized MT pop(){
            if(index == 0){
                try {
                    this.wait();
                }catch(InterruptedException ex){
                    ex.printStackTrace();
                }
            }
            this.notify();
            index -- ;
            return mts[index];
        }
    }
    
    class Producer implements Runnable{
        SyncStack stack = null;
        
        public Producer(SyncStack stack) {
            this.stack = stack;
        }
        public void run(){
            for(int i = 0 ; i < 20 ; i ++){
                MT mt = new MT(i);
                stack.push(mt);
                System.out.println("生产了:" + mt);
                try{
                    Thread.sleep((int)(Math.random()*200));
                }catch(InterruptedException ex){
                    ex.printStackTrace();
                }
            }
        }
    }
    
    class Consumer implements Runnable{
        
        SyncStack stack = null;
        
        public Consumer(SyncStack stack) {
            this.stack = stack;
        }
        
        public void run(){
            for(int i = 0 ; i < 20 ; i ++){
                MT mt = stack.pop();
                System.out.println("消费了:" + mt);
                try{
                    Thread.sleep((int)(Math.random()*1000));
                }catch(InterruptedException ex){
                    ex.printStackTrace();
                }
            }
        }
    }
  • 相关阅读:
    Oracle decode函数
    Flink笔记
    httpclient之put 方法(参数为json类型)
    XMLHTTPRequest的理解 及 SpringMvc请求和响应xml数据
    SQL获取本周,上周,本月,上月第一天和最后一天 注:本周从周一到周天
    Other
    Sql根据起止日期生成时间列表
    sql 在not in 子查询有null值情况下经常出现的陷阱
    sql 判断一个表的数据不在另一个表中
    查看系统触发器
  • 原文地址:https://www.cnblogs.com/xuewuzhijing95hao/p/7127118.html
Copyright © 2011-2022 走看看