BlockingQueue,阻塞队列实现线程通信

可阻塞队列

  (1) 队列包含固定长度的队列和不固定长度的队列。
  (2)什么是可阻塞队列,阻塞队列的作用与实际应用,阻塞队列的实现原理
ArrayBlockingQueue
    看ArrayBlockingQueue类的帮助文档,其中有各个方法的区别对比的表格
    只有put方法和take方法才具有阻塞功能
 (3)用3个空间的队列来演示阻塞队列的功能和效果
 (4)用两个具有1个空间的队列来实现同步通知的功能
 (5)阻塞队列与Semaphore有些相似,但也不同。阻塞队列是一方存放数据,另一方释放数据,Semaphore
通常则是由同一方设置和释放信号量

可用阻塞队列实现线程通信

package com.ronbay.thread.timer;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;


public class BlockingQueueCommunication {

	public static void main(String[] args) {
		final Business business = new Business();
		
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				for (int i = 0; i < 50; i++) {
					business.sub(i);
				}
				
			}
		}).start();
		
		for (int i = 0; i < 50; i++) {
			business.main(i);
		}
	}
  static class Business{
	  BlockingQueue<Integer> queue1 = new ArrayBlockingQueue<Integer>(1);
	  BlockingQueue<Integer> queue2 = new ArrayBlockingQueue<Integer>(1);
	  //匿名构造方法,运行时机在任何构造方法之前,创建几次对象就调用几次
	  {
		  try {
			  System.out.println("dvsdvsdvsxxxasdcasfas");
			  queue2.put(1);
		} catch (Exception e) {
		}
	  }
	  public  void sub(int i ){
		  try {
			queue1.put(1);
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		}
		  for (int j = 1; j <= 10; j++) {
			System.out.println("sub thread sequence of " + j + ",loop of " + i);
		}
		try {
			queue2.take();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	  }
	  public  void main(int i){
		  try {
			queue2.put(1);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		  for (int j = 1; j <= 100; j++) {
			  System.out.println("main thread sequence of " + j + ",loop of " + i);
		}
		  
		  try {
			queue1.take();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		  
	  }
  }
}

猜你喜欢

转载自ronbay.iteye.com/blog/2297837