• 阻塞队列


     1 package unit;
     2 
     3 import java.util.concurrent.ArrayBlockingQueue;
     4 
     5 /**
     6  * 阻塞队列
     7  * @author 54304
     8  *
     9  */
    10 public class BlockingQueue {
    11     private int queueSize = 10;
    12     private ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(queueSize);
    13     int m = 0;
    14     int n = 0;
    15     int k = 0;
    16     public static void main(String[] args) throws InterruptedException  {
    17         BlockingQueue test = new BlockingQueue();
    18         Producer producer = test.new Producer();
    19         Consumer consumer = test.new Consumer();
    20         
    21         producer.start();
    22         consumer.start();
    23     }
    24      
    25     class Consumer extends Thread{
    26          
    27         @Override
    28         public void run() {
    29             consume();
    30         }
    31          
    32         private void consume() {
    33             while(true){
    34                 try {
    35                     queue.take();
    36                     Thread.sleep(1000);
    37                     System.out.println("队列有: "+queue.size()+" 个 元素"+"  编号"+ ++m + " 减少"+ "   减少次数:"+ ++n);
    38                 } catch (InterruptedException e) {
    39                     e.printStackTrace();
    40                 }
    41             }
    42         }
    43     }
    44      
    45     class Producer extends Thread{
    46          
    47         @Override
    48         public void run() {
    49             produce();
    50         }
    51          
    52         private void produce() {
    53             for(int i=0; i<10; i++){
    54                 try {
    55                     queue.put(1);
    56                     Thread.sleep(1000);
    57                     System.out.println("队列有: "+queue.size()+" 个 元素"+"  编号"+ ++m + " 添加"+ "   添加次数:"+ ++k);
    58                 } catch (InterruptedException e) {
    59                     e.printStackTrace();
    60                 }
    61             }
    62         }
    63     }
    64 }
  • 相关阅读:
    VC++删除浮动工具条中“关闭”按钮
    automation无法创建对象
    SQL Server 不产生日志
    收缩数据文件
    VB DoEvents用法
    Sql Server添加用户
    Winsock错误代码一览表
    监控数据库性能的sql
    数据库日志文件清理脚本
    VB 中资源文件的多种使用技巧
  • 原文地址:https://www.cnblogs.com/redhat0019/p/8034182.html
Copyright © 2020-2023  润新知