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();
            
        }
    
    }
    代码参考
  • 相关阅读:
    django 模型层
    django 模板层
    django的视图层
    django-2的路由层(URLconf)
    django简介
    [Codeforces] 650A
    [codevs2916] 校门外的树2
    [Codevs 1690] 开关灯
    codevs3027线段覆盖2(DP)题解
    BC#65T4 ZYB's Tree
  • 原文地址:https://www.cnblogs.com/haizinihao/p/14764705.html
Copyright © 2011-2022 走看看