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();
        
    }

}
代码参考
原文地址:https://www.cnblogs.com/haizinihao/p/14764705.html