자바 Array BlockingQueue 사용 예시

2479 단어
import java.util.concurrent.ArrayBlockingQueue;


public class TestArrayBlocking {
	public static void main(String[] args) throws Exception {
//		insertBlocking();
//		fetchBlocking();
		
		ArrayBlockingQueue<String> abq = new ArrayBlockingQueue<String>(10);
		testProducerConsumer(abq);
		
	}
	
	   
	/**
	 *        ArrayBlockingQueue         :        ,            ,          。
	 */
	public static void insertBlocking() throws InterruptedException {
		ArrayBlockingQueue<String> names = new ArrayBlockingQueue<String>(1);
		names.put("a");
		//                 
		names.put("b");
		
		System.out.println("      ...");
	}
	
	/**
	 *        ArrayBlockingQueue         :      ,           ,        。
	 * 
	 */
	public static void fetchBlocking() throws InterruptedException {
		ArrayBlockingQueue<String> names = new ArrayBlockingQueue<String>(1);
		names.put("a");
		names.remove();
		names.remove();
		names.put("b");
		
		System.out.println("      ...");
	}
	
	   
	/**
	 * @                 
	 *                      :
	 * 1.                   
	 * 2.                       ,     。
	 * @param abq 
	 */
	public static void testProducerConsumer (ArrayBlockingQueue<String> abq) {
		Thread tConsumer = new Consumer(abq);
		Thread tProducer = new Producer(abq);
		tConsumer.start();
		tProducer.start();
	}
	
}

   
/**            
 * @        
 *    
 */       
class Consumer extends Thread {
	ArrayBlockingQueue<String> abq = null;

	public Consumer(ArrayBlockingQueue<String> abq) {
		super();
		this.abq = abq;
	}
	
	@Override
	public void run() {
		while(true) {
			try{
				Thread.sleep(500);
				String msg = abq.remove();
				System.out.println("   :===="+msg+"\t     :"+abq.size());
			} catch (Exception e) {
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
			}
		}
	}
}

   
/**            
 * @        
 *    
 */       
class Producer extends Thread {
	ArrayBlockingQueue<String> abq = null;

	public Producer(ArrayBlockingQueue<String> abq) {
		this.abq = abq;
	}

	@Override
	public void run() {
		int i = 0;
		while(true) {
			try {
				Thread.sleep(1000);
				abq.put(""+i);
				System.out.println("    :===="+i+"\t     :"+abq.size());
				i++;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}


좋은 웹페이지 즐겨찾기