• 水池进水和出水两个线程问题


    问题描述:

    有一个水池,水池的容量是固定 的500L,一边为进水口,一边为出水口.要求,进水与放水不能同时进行.

    水池一旦满了不能继续注水,一旦放空了,不可以继续放水. 进水的速度5L/s , 放水的速度2L/s

    这是一个多线程问题

     1 /*
     2  作业1:有一个水池,水池的容量是固定 的500L,一边为进水口,一边为出水口.要求,进水与放水不能同时进行.
     3  水池一旦满了不能继续注水,一旦放空了,不可以继续放水. 进水的速度5L/s ,  放水的速度2L/s  
     4  */
     5 
     6 class Pool {
     7 
     8     int capacity = 0;
     9 
    10 }
    11 
    12 class Inlet extends Thread {
    13 
    14     Pool p;
    15 
    16     public Inlet(Pool p) {
    17         this.p = p;
    18     }
    19     
    20     @Override
    21     public void run() {
    22         while(true){
    23             synchronized (p) {
    24                 if((p.capacity + 5) <= 500){
    25                     System.out.println("进水中,水池容量为:"+(p.capacity + 5));
    26                     p.capacity += 5;
    27                     p.notify();
    28                 }else{
    29                     System.out.println("水池水满了");
    30                     try {
    31                         p.wait();
    32                     } catch (InterruptedException e) {
    33                         e.printStackTrace();
    34                     }
    35                 }
    36             }
    37         }
    38     }
    39 
    40 }
    41 
    42 // 出水
    43 class Outlet extends Thread {
    44 
    45     Pool p;
    46 
    47     public Outlet(Pool p) {
    48         this.p = p;
    49     }
    50     
    51     @Override
    52     public void run() {
    53         
    54         while(true){
    55             synchronized (p) {
    56                 if((p.capacity - 2) >= 0){
    57                     System.out.println("水池出水中,水池容量为:"+(p.capacity - 2));
    58                     p.capacity -= 2;
    59                     p.notify();
    60                 }else{
    61                     System.out.println("水池没水了");
    62                     try {
    63                         p.wait();
    64                     } catch (InterruptedException e) {
    65                         e.printStackTrace();
    66                     }
    67                 }
    68             }
    69         }
    70     }
    71 
    72 }
    73 
    74 public class Zuoye1 {
    75 
    76     public static void main(String[] args) {
    77         Pool p = new Pool();
    78         Inlet in = new Inlet(p);
    79         Outlet out = new Outlet(p);
    80         in.start();
    81         out.start();
    82 
    83     }
    84 
    85 }
  • 相关阅读:
    mac 调整Launchpad行列数目
    查询及删除重复记录的SQL语句
    Linux中删除特殊符号文件名文件
    Mac 如何寻找Mac自带的IDLE
    Spring、Spring MVC、MyBatis 整合文件配置详解
    虚拟机下安装win7
    kali-linux 安装
    selenium 元素定位
    selenium 启动、窗口、获取标题
    python+ selenium + webdriver的环境准备
  • 原文地址:https://www.cnblogs.com/bequt/p/5656080.html
Copyright © 2020-2023  润新知