//进水 class Inflow implements Runnable{ //水对象 Water wat; public Inflow(Water w){ this.wat = w; } @Override public void run() { //进水 while (true) { synchronized (wat) { while (true) { if (wat.count >= 50) { wat.notify(); try { wat.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } try { //睡眠线程 Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } wat.count++; System.out.println("现在是在进水,水量为:" + wat.count); } } } } } //出水 class Outflow implements Runnable{ Water wat; public Outflow(Water w){ this.wat = w; } @Override public void run() { //出水 while (true) { //线程锁 synchronized (wat) { while (true) { if (wat.count <= 0) { wat.notify(); try { wat.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } wat.count--; System.out.println("现在是在放水,剩余水量为:" + wat.count); } } } } } class Water{ int count = 50; } public class demo5 { public static void main(String[] args) { //创建水对象 Water Water = new Water(); //进水对象 Inflow in = new Inflow(Water); //放水对象 Outflow out = new Outflow(Water); // Thread thread = new Thread(in); Thread the = new Thread(out); //开启线程 thread.start(); the.start(); } }
时间: 2024-10-06 20:35:10