用java多线程实现一个简单的水池进出水问题

需求:

有一个水池100L,有出水口和入水口,出水口和入水口不能同时打开,入水口每次注入5L水,出水口每次出4L水,如果池子注满水,或者池子中没有水就停止。
使用继承Thread类的方式编写出水口,使用实现Runnable方式编写入水口,运行结果。

package pool;

/**
 * 
 * 出水口outfall 入水口inflow 水池pool
 *
 */

class  Waterpool{
	public static int pool =5;
	static boolean isTrue = true;
}	
class Outfall extends Thread {
	Waterpool w;
	public Outfall(Waterpool w) {
			super();
			this.w =w;
		}
		@Override
		public void run() {	
			while (Waterpool.isTrue) {
				synchronized (w) {
					if(Waterpool.pool>995 && Waterpool.pool<1000){
						System.out.println("加水"+(1000-Waterpool.pool)+"L后水满了");
						Waterpool.pool=1000;
						Waterpool.isTrue= false;
					}else if (Waterpool.pool < 1000 && Waterpool.pool>0) {
						Waterpool.pool=Waterpool.pool+5;
						System.out.println("加水5L当前水量后"+Waterpool.pool);
					}else {
						System.out.println("不能加水了");
						Waterpool.isTrue= false;
						
					}
					
				}
				
			}

		}

	}
	class Inflow implements Runnable {
		Waterpool w;
		public Inflow(Waterpool w) {
			this.w =w;
		}
		@Override
		public void run() {
			while (Waterpool.isTrue) {
				synchronized (w) {
					if(Waterpool.pool>0 && Waterpool.pool<4) {
						System.out.println("出水"+Waterpool.pool+"L后没水了");
						Waterpool.pool=0;
						Waterpool.isTrue= false;
					}else if (Waterpool.pool>0 && Waterpool.pool<1000) {
						Waterpool.pool = Waterpool.pool-4;
						System.out.println("出水4L后当前水量"+Waterpool.pool);
					}else {
						System.out.println("不能放水了");
						Waterpool.isTrue= false;
						
					}
				}
				
			}
		}
	}

	public class Homework {
	       public static void main(String[] args) {
	    	    Waterpool w =new Waterpool();
			    Outfall outfall =new Outfall(w);
				Inflow inflow = new Inflow(w);
				outfall.start();
				Thread in = new Thread(inflow);
				in.start();				
	}
}
之后多次运行求证结果是不是还有线程安全问题
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值