Producer-Consumer Model

Wait for notification mechanism:

      1. The wait() method: Stops the thread currently executing the code. The wait() method is a method of the Object class. This method is used to place the current thread in the "pre-execution queue", and when the code where wait() is located Execution is stopped at this point until notified or interrupted.

public class Test5_4{
	public static void main(String[] args) throws InterruptedException {
		Object object =  new Object();
		synchronized (object) {
			System.out.println("Waiting");
			object.wait();
			System.out.println("Waiting is complete");
		}
		System.out.println("main method ended");
	}
}

      If it waits until object.wait() is executed, the program must not wait like this forever. At this time, you need to use another method to wake up the method notify() 

     2. notify() method: notify() method is also called in a synchronized method or synchronized code block, that is, before calling, the thread must also obtain the object-level lock of the object. If the call to notify() does not hold the appropriate lock, an IllegalMonitorStateException will be thrown. After executing the notify method, the current thread will not release the object lock immediately, and the thread in the wait state will not immediately acquire the object lock. It has to wait until the thread executing the notify method finishes executing the program, that is, after exiting the synchronized code block, the current The thread will release the lock, and the thread where the wait state is present will acquire the object lock.

//notify method
class MyRunnable implements Runnable{
	private Object object;
	private boolean flag;
	public MyRunnable(boolean flag,Object object) {
		super();
		this.object = object;
		this.flag = flag;
	}
	public void waitMethod() {
		synchronized (object) {
			try {
				while(true) {
					System.out.println("wait()方法开始:"+Thread.currentThread().getName());
					object.wait();
					System.out.println("wait()方法结束:"+Thread.currentThread().getName());
					return;
					}
				}catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace ();
				}
		  }
	}
	public void notifyMethod() {
		synchronized (object) {
			try {
					System.out.println("notify()方法开始:"+Thread.currentThread().getName());
					object.wait();
					System.out.println("notify()方法结束:"+Thread.currentThread().getName());
					return;
			}catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace ();
				}
		  }
	}

	public void run() {
		 if (flag) {            
			 this.waitMethod();   
			 } else {  
				 this.notifyMethod();   
				 }
	}
}
public class Test5_4{
	public static void main(String[] args) throws InterruptedException {
		 Object object = new Object();      
		 MyRunnable waitThread = new MyRunnable(true, object);     
		 MyRunnable notifyThread = new MyRunnable(false, object);       
		 Thread thread1 = new Thread(waitThread, "wait线程");        
		 Thread thread2 = new Thread(notifyThread, "notify线程");      
		 thread1.start();        
		 Thread.sleep(1000);     
		 thread2.start();        
		 System.out.println("main method ends!!");
	}
}

   wait stops the thread, notify keeps the stopped thread running. And wait, notify must be used in the synchronized synchronization method or code block.

Producer Consumer Model:

       The producer-consumer pattern solves the problem of strong coupling between producers and consumers through a container. Producers and consumers do not communicate directly with each other, but communicate through blocking queues. Therefore, after producers produce data, they do not need to wait for consumers to process data, but throw them directly to blocking queues. Consumers do not ask producers for data, but Taken directly from the blocking queue, the blocking queue is equivalent to a buffer, balancing the processing capabilities of producers and consumers.

// one production and one consumption
class Goods{
	//Item Name
	private String goodName;
	//number of the stuffs
	private int goodNum;
	//production method
	public synchronized void pro(String goodName) throws InterruptedException {
		//There are still unconsumed products at this time
		if(this.goodNum > 0) {
			System.out.println("There are unconsumed products, waiting for consumers");
			wait();
		}
		this.goodName = goodName;
		this.goodNum = goodNum + 1;
		Thread.sleep(1000);
		System.out.println("生产"+toString());
		//Notify the consumer to consume after the product is produced
		notify();
	}
	//consume method
	public synchronized void con() throws InterruptedException {
		if(this.goodNum == 0) {
			System.out.println("The product has been consumed, please wait a moment");
			wait();
		}
		this.goodNum = goodNum -1;
		Thread.sleep(1000);
		System.out.println("消费"+toString());
		//The product is consumed, notify the producer to produce
		notify();
	}
	public String toString() {
		return "Goods [goodName = "+goodName +" , goodNum = "+goodNum + "]";
	}
}
// consumer class
class Produce implements Runnable{
	private Goods goods;
	public Produce(Goods goods) {
		super();
		this.goods = goods;
	}
	public void run() {
		while(true) {
			try {
				this.goods.pro("Car");
			} catch (InterruptedException e) {
				e.printStackTrace ();
			}
		}
	}
}
//producer class
class Consumer implements Runnable{
	private Goods goods;
	public Consumer(Goods goods) {
		super();
		this.goods = goods;
	}
	public void run() {
		while(true) {
			try {
				this.goods.con();
			} catch (InterruptedException e) {
				e.printStackTrace ();
			}
		
		}
	}
}
public class Test5_4{
	public static void main(String[] args) throws InterruptedException {
		Goods goods =  new Goods();
		Produce produce =  new Produce(goods);
		Consumer consumer =  new Consumer(goods);
		Thread produceThread = new Thread(produce, "producer thread");
		Thread consumerThread = new Thread(consumer,"consumer thread");
		consumerThread.start();
		Thread.sleep(1000);
		produceThread.start();
	}
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326069076&siteId=291194637