zoukankan      html  css  js  c++  java
  • java 中之经典多线程问题——进水放水

    public class ThreadInflowAndOutflow {

    public static void main(String[] args) {
    Water water=new Water();

    inflow fi=new inflow(water);
    outflow of=new outflow(water);

    Thread t1=new Thread(fi);
    Thread t2=new Thread(of);

    t1.start();
    t2.start();

    }

    }


    class Water{

    int count = 50;
    }
    class inflow implements Runnable{


    Water water;
    public inflow(Water water){
    this.water=water;
    }

    @Override
    public void run() {

    while(true){
    synchronized (water) {
    while(true){
    if(water.count>=20){
    water.notify();

    try {
    water.wait();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }

    try {
    Thread.sleep(1000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }

    water.count+=3;
    System.out.println("现在是在进水,水量为:"+water.count);
    }
    }
    }
    }

    }


    class outflow implements Runnable{

    Water water;
    public outflow(Water water){
    this.water=water;
    }


    @Override
    public void run() {

    while(true){
    synchronized (water) {
    while(true){
    if(water.count<=30){
    water.notify();

    try {
    water.wait();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }

    }

    try {
    Thread.sleep(1000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }

    water.count--;
    System.out.println("现在是放水,剩余水量为:"+water.count);
    }
    }
    }

    }

    }

  • 相关阅读:
    学习视屏
    Spring 和 MyBatis 环境整合
    struts2 多文件下载
    struts2的单文件下载
    很好的验证码
    Oracle 存储过程
    Oracle序列
    struts2 的多文件上传
    struts2的单文件上传
    NETBEAN 启动报错 CANNOT LOCATE JAVA INSTALLATION IN SPECIFIED JDKHOME的解决办法
  • 原文地址:https://www.cnblogs.com/1a2b/p/8919208.html
Copyright © 2011-2022 走看看