`
阿尔萨斯
  • 浏览: 4203654 次
社区版块
存档分类
最新评论

BlockingQueue: 阻塞队列 接口

 
阅读更多
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
/*
 * BlockingQueue
 * 			put()—— 队列满后,等待有空间了才能放入,即等  take()
 * 			take()—— 队列空后,等待放入了元素才才能取出,即等 put()
 * 
 * 两个 含一个空间的阻塞队列,实现 同步 通知功能:两条线程交互执行
 */
public class BlockQueueCommunication {
	public static void main(String[] args) {
		final MyThread m = new MyThread();

		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
					while(true)m.sub1();
			}
		}).start();

		while(true)
			m.main();
	}
	static class MyThread {
		BlockingQueue queue1 = new ArrayBlockingQueue(1);
		BlockingQueue queue2 = new ArrayBlockingQueue(1);
		{
			try {
				queue2.put(1);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		public void main() {
			try {
				queue1.put(1);
				Thread.sleep((long)(Math.random()*100));
				System.out.println("main:administrators");
				queue2.take();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		public void sub1() {
			try {
				queue2.put(1);
				Thread.sleep((long)(Math.random()*100));
				System.out.println("sub1:system database admin");
				queue1.take();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics