zoukankan      html  css  js  c++  java
  • Java001_多线程作业

    生产者和消费者案例01

    class Queue{
        private int n;
        
        boolean flag = false;
        public synchronized void set(int n) {
            if(flag) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            System.out.println("生产"+n);
            flag = true;
            notifyAll();
            this.n = n;
        }
        
        public synchronized  int get() {
            if (!flag) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            System.out.println("消费  "+n);
            notifyAll();
            flag = false;
            return n;
        }
            
    }
    
    class Producer implements Runnable{
        Queue q ;
        
        public Producer(Queue q) {
            this.q = q;
        }
    
        @Override
        public void run() {
            int n = 0;
            while(true) {
                q.set(n++);
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            
        }
    }
    
    
    class Consumer implements Runnable{
        Queue q;
        
        public Consumer(Queue q) {
            this.q = q;
        }
        
        @Override
        public void run() {
            while(true) {
                q.get();
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            
        }
        
    }
    
    
    
    public class j01_线程作业 {
    
        public static void main(String[] args) {
            Queue q = new Queue();
            new Thread(new Producer(q)).start();
            new Thread(new Consumer(q)).start();
            
        }
    
    }
    代码参考
  • 相关阅读:
    安装xml2js出现npm ERR! code E404 npm ERR! 404 Not Found: event-stream@3.3.6
    ie的盒模型和标准模型
    vue-生命周期
    Vue2.5入门-2
    Vue2.5入门-1
    Vue2.5入门-3
    理解 ajax、fetch和axios
    sublime install package没反应,以及安装后没有出现install package选项
    6-创建官网
    numpy数组常用计算
  • 原文地址:https://www.cnblogs.com/haizinihao/p/14764705.html
Copyright © 2011-2022 走看看