zoukankan      html  css  js  c++  java
  • 管程法

    /**

    • 管程法, 测试生产者和消费者
      */
      public class TestPC {
      public static void main(String[] args) {
      SynContainer container = new SynContainer();
      Producter producter = new Producter(container);
      Customer customer = new Customer(container);
      producter.start();
      customer.start();
      }
      }
      //需要生产者、消费者、产品、缓冲区
      class Producter extends Thread{
      SynContainer container;

      public Producter(SynContainer container) {
      this.container = container;
      }

      @Override
      public void run() {
      for (int i = 0; i < 100; i++) {
      this.container.push(new Chicken(i));
      System.out.println("生产了"+i+"只鸡");
      }
      }
      }
      class Customer extends Thread{
      SynContainer container;

      public Customer(SynContainer container) {
      this.container = container;
      }

      @Override
      public void run() {
      for (int i = 0; i < 100; i++) {
      System.out.println("消费了"+container.pop().id+"只鸡");
      }
      }
      }
      class Chicken{
      int id; //编号

      public Chicken(int id) {
      this.id = id;
      }
      }
      class SynContainer {
      // 容器大小
      Chicken[] chickens = new Chicken[10];
      // 计数
      int count = 0;
      public synchronized void push(Chicken chicken){
      if(count == chickens.length){
      try {
      // 等待消费者消费
      this.wait();
      } catch (InterruptedException e) {
      e.printStackTrace();
      }
      }
      chickens[count] = chicken;
      count++;
      // 通知消费者消费
      this.notifyAll();
      }

      public synchronized Chicken pop(){
      if(count == 0){
      try {
      // 等待生产者生产
      this.wait();
      } catch (InterruptedException e) {
      e.printStackTrace();
      }
      }
      count--;
      Chicken chicken = chickens[count];
      // 通知生产者生产
      this.notifyAll();
      return chicken;
      }
      }

  • 相关阅读:
    2.4.6 处理表单 的 工作原理的解释
    nginx proxy模块
    nginx负载均衡模块
    Oracle正在执行和执行过的SQL语句
    nginx
    linux :故障提示:Error:No suitable device found: no device found for connection "System eth0"
    memcached
    一致性哈希算法(consistent hashing)(转)
    大规模网站sesson会话保持思路及实践配置
    AB压力测试工具
  • 原文地址:https://www.cnblogs.com/gbhh/p/13768119.html
Copyright © 2011-2022 走看看