package ru.apetrov.producerCustomer;

import java.util.LinkedList;
import java.util.Queue;

/**
 * Created by Andrey on 26.07.2017.
 */
public class ProducerCustomer<E> {

    private Queue<E> queue;

    private boolean isLock = false;

    public ProducerCustomer() {
        this.queue = new LinkedList<E>();
    }

    public void add(E element) {
        synchronized (this) {
            while (this.isLock) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        this.isLock = true;
        this.queue.add(element);
        System.out.printf("%s add in queue \n", element);

        synchronized (this) {
            notify();
            this.isLock = false;
        }
    }

    public void get() {
        synchronized (this) {
            while (this.isLock || this.queue.peek() == null) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        this.isLock = true;
        System.out.printf("get element %s in queue\n", this.queue.poll());

        synchronized (this) {
            notify();
            this.isLock = false;
        }
    }

    public static void main(String[] args) {
        ProducerCustomer<Integer> prodCust = new ProducerCustomer<>();
        Thread producer = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 1000; i++) {
                    prodCust.add(i);
                }
            }
        });

        Thread customer = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 1000; i++) {
                    prodCust.get();
                }
            }
        });

        producer.start();
        customer.start();
    }
}

@@ -363,32 +363,38 @@
 nchronized (this
+.queue
 ) %7B%0A            
@@ -449,32 +449,43 @@
                 
+this.queue.
 wait();%0A        
@@ -614,36 +614,8 @@
   %7D%0A
-        this.isLock = true;%0A
     
@@ -720,32 +720,38 @@
 nchronized (this
+.queue
 ) %7B%0A            
@@ -742,32 +742,43 @@
 ) %7B%0A            
+this.queue.
 notify();%0A      
@@ -789,36 +789,35 @@
   this.isLock = 
-fals
+tru
 e;%0A        %7D%0A   
@@ -862,32 +862,38 @@
 nchronized (this
+.queue
 ) %7B%0A            
@@ -891,32 +891,33 @@
          while (
+!
 this.isLock %7C%7C t
@@ -986,16 +986,27 @@
         
+this.queue.
 wait();%0A
@@ -1143,36 +1143,8 @@
   %7D%0A
-        this.isLock = true;%0A
     
@@ -1241,16 +1241,22 @@
 ed (this
+.queue
 ) %7B%0A    
@@ -1263,16 +1263,27 @@
         
+this.queue.
 notify()
@@ -1588,34 +1588,32 @@
 nt i = 0; i %3C 10
-00
 ; i++) %7B%0A       
@@ -1833,18 +1833,16 @@
 ; i %3C 10
-00
 ; i++) %7B

update 6.4.1