首页 > 代码库 > java中用线程解决进出水问题
java中用线程解决进出水问题
//进水 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(); } }
java中用线程解决进出水问题
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。