zoukankan      html  css  js  c++  java
  • 阻塞队列

     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 }
  • 相关阅读:
    javascript之数组操作
    python中的类中属性元素加self.和不加self.的区别
    Q查询
    jQuery EasyUI的各历史版本和应用
    了解Entity Framework中事务处理
    C#中Abstract和Virtual的区别
    控制器post参数接收
    存储过程调用存储过程
    表变量、临时表(with as ,create table)
    LINQ TO SQL 实现无限递归查询
  • 原文地址:https://www.cnblogs.com/redhat0019/p/8034182.html
Copyright © 2011-2022 走看看