标签:
问题:有一个水池,水池的容量是固定 的20L,一边为进水口,一边为出水口.要求,进水与放水不能同时进行.
水池一旦满了不能继续注水,一旦放空了,不可以继续放水. 进水的速度5L/s , 放水的速度2L/s
分析:创建2个线程,一个进水,一个用于放水。这里以秒为单位,进水每次进5L,放水每次放2L
如果当前水量小于2L,则不能放水。如果当前水量大于15L,则不能加水。
具体实现如下:
package com.dongbin.thread; //容量 class Water{ private double total = 0; public double getTotal() { return total; } public void setTotal(double total) { this.total = total; } } //进水 class InputWater extends Thread{ private Water water; public InputWater(Water water) { this.water = water; } @Override public void run() { while (true) { synchronized (water) { if (water.getTotal() <= 15) { // 进水 按秒进 try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } water.setTotal(water.getTotal() + 5); System.out.println(Thread.currentThread().getName() + ": 进水5L,目前水量" + water.getTotal() + "L!!!"); water.notify();// 唤醒放水线程 } else { System.out.println(Thread.currentThread().getName() + ": 不能再加水了!!! "); try { water.wait();// 进水线程等待 } catch (InterruptedException e) { e.printStackTrace(); } } } } } } //放水 class OutWater extends Thread{ private Water water; public OutWater(Water water) { this.water = water; } @Override public void run() { while (true) { synchronized (water) { if (water.getTotal() >= 2) { // 放水 try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } water.setTotal(water.getTotal() - 2); System.out.println(Thread.currentThread().getName() + ": 放水2L,目前水量" + water.getTotal() + "L"); water.notify();// 唤醒进水线程 } else { // 等待加水 System.out.println(Thread.currentThread().getName() + ":不能放水了!!! "); try { water.wait();// 放水线程等待 } catch (InterruptedException e) { e.printStackTrace(); } } } } } } public class Test { public static void main(String[] args) { Water water = new Water(); InputWater inputWater = new InputWater(water); inputWater.setName("进水线程"); OutWater outWater = new OutWater(water); outWater.setName("放水线程"); //启动线程 inputWater.start(); outWater.start(); } }
结果:
标签:
原文地址:http://www.cnblogs.com/b-dong/p/5883725.html