一個水池容量爲1000個單位,水池每秒進水4個單位,每秒放水1個單位,求水池滿了後的時間?


package com.xxzzycq2.thread;

public class Water
{
	public static int count = 0;
	
	public static int time = 0;
	
	public static void main(String[] args)
	{
		Thread t1 = new In();
		Thread t2 = new Out();
		
		t1.start();
		t2.start();
	}
}

class In extends Thread
{
	public void run()
	{
		while(Water.count < 1000)
		{
			synchronized (Water.class)
			{
				try
				{
					Thread.sleep(1000);
					
					Water.count += 4;
					
					System.out.println(Water.count);
					
					Water.time++;
					
					if(Water.count >= 1000)
					{
						System.out.println(Water.time);
						
						System.exit(0);
					}
				}
				catch (InterruptedException e)
				{
					e.printStackTrace();
				}
			}
		}
	}
	
	
}

class Out extends Thread
{
	public void run()
	{
		while(Water.count < 1000)
		{
			synchronized (Water.class)
			{
				try
				{
					Thread.sleep(1000);
					
					Water.count -= 1;
					
					System.out.println(Water.count);
					
					Water.time++;
					
				}
				catch (InterruptedException e)
				{
					e.printStackTrace();
				}
			}
		}
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章