java中用线程解决进出水问题

Posted ljyhyy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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中用线程解决进出水问题的主要内容,如果未能解决你的问题,请参考以下文章

Java多线程的临界资源问题

为啥我们需要进出组装说明? [关闭]

如何在android studio中用另一个片段替换一个片段

有没有办法关闭代码片段中的命名建议?

CTS测试CtsWindowManagerDeviceTestCases模块的testShowWhenLockedImeActivityAndShowSoftInput测试fail项解决方法(代码片段

急急急~~求JAVA中用方法写出一个银行ATM取款机的代码怎么写!!