热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

12、Java并发编程:阻塞队列

 private int queueSize= 10; private PriorityQueueIntegerqueue= new PriorityQueueInteger

 private int queueSize = 10;
 private PriorityQueue Integer queue = new PriorityQueue Integer (queueSize);
 
 public static void main(String[] args)  {
 Test test = new Test();
 Producer producer = test.new Producer();
 Consumer cOnsumer= test.new Consumer();
 
 producer.start();
 consumer.start();
 }
 
 class Consumer extends Thread{
 
 @Override
 public void run() {
 consume();
 }
 
 private void consume() {
 while(true){
 synchronized (queue) {
 while(queue.size() == 0){
 try {
 System.out.println("队列空,等待数据");
 queue.wait();
 } catch (InterruptedException e) {
 e.printStackTrace();
 queue.notify();
 }
 }
 queue.poll(); //每次移走队首元素
 queue.notify();
 System.out.println("从队列取走一个元素,队列剩余"+queue.size()+"个元素");
 }
 }
 }
 }
 
 class Producer extends Thread{
 
 @Override
 public void run() {
 produce();
 }
 
 private void produce() {
 while(true){
 synchronized (queue) {
 while(queue.size() == queueSize){
 try {
 System.out.println("队列满,等待有空余空间");
 queue.wait();
 } catch (InterruptedException e) {
 e.printStackTrace();
 queue.notify();
 }
 }
 queue.offer(1); //每次插入一个元素
 queue.notify();
 System.out.println("向队列取中插入一个元素,队列剩余空间:"+(queueSize-queue.size()));
 }
 }
 }
 }


推荐阅读
author-avatar
一只幸福的汪星人
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有