wait 와 notify 를 사용 하여 생산자 소비자 모델 실현

2823 단어 자바
package ProducerAndConsumer;

import java.util.ArrayList;
import java.util.List;

/**
 * 1,    wait,notifyAll notify  ,             。java     ,      ,         ,   
 *       。
 * 2,     wait  ,           (     ),    。
 * 3,     notify  ,                   ,        ,        。notifyAll               。
 * 4,  ,wait,notifyAll notify               ,    ,   synchronized           。   IllegalMonitorStateException
 * 5,    :https://www.cnblogs.com/qlqwjy/p/10115756.html,    !
 */
public class WaitNotifyTest {
	
	/**
	 *                 ,    list  “  ”。
	 *                    ,       list   ,          ,         。
	 */

	public static void main(String[] args) throws Exception {
		final List list=new ArrayList<>();
		
		/**
		 * 1,   1      2           。
		 * 2,      ,        ,                。  list  ,     。       “  ”(remove  ),            ,
		 *       。
		 * 3, while(list.size()==0){}       while    if ?    if        ,         ,   list  ,           ,
		 *                       ,      wait     ,      list    ,             (remove  ),     
		 *       (remove  ),        。
		 */
		Thread consumer1=new Thread(()-> {
				synchronized (list) {
					while(true){
						while(list.size()==0){
							try {
								System.out.println(Thread.currentThread().getName()+"   ");
								list.wait();
							} catch (InterruptedException e) {
							}
						}
						System.out.println(Thread.currentThread().getName()+"       ");
						list.remove(0);
						list.notifyAll();
					}
				}
		},"   1");
		
		Thread consumer2=new Thread(()->{
			synchronized (list) {
				while(true){
					while(list.size()==0){
						try {
							System.out.println(Thread.currentThread().getName()+"   ");
							list.wait();
						} catch (InterruptedException e) {
						}
					}
					System.out.println(Thread.currentThread().getName()+"       ");
					list.remove(0);
					list.notifyAll();
				}
			}
			
		},"   2");
		
		/**
		 *      ,      ,     (add  ),            ,        。               。
		 */
		
		Thread producer1=new Thread(()->{
			
			synchronized (list) {
				
				for (int i = 0; i < 10; i++) {
					if(list.isEmpty()){
						System.out.println(Thread.currentThread().getName()+"   "+i+"   ");
						list.add(i+"   ");
					}else{
						try {
							list.notifyAll();
							list.wait();
						} catch (InterruptedException e) {
						}
					}
				}
			}
					
		},"   1");
		
		
		producer1.start();
		Thread.sleep(100);
		consumer1.start();
		consumer2.start();
		
	}

}

실행 결과:
   1   0   
   2       
   2   
   1   2   
   2       
   2   
   1   4   
   2       
   2   
   1   6   
   2       
   2   
   1   8   
   2       
   2   
   1   

좋은 웹페이지 즐겨찾기