武松打虎进化版

[代码] [Java]代码 import java.util.*;
class Q
{
	boolean b = false;
	Random r = null;
	//武松的血条
	int wusongblood = 10;
	//老虎的血条
	int tiggerblood = 10;
	public Q()
	{
		r = new Random();
	}
	// http://www.haokk123.info/linked/20130424.do 武松侵犯
	public synchronized void wugong()
	{
		if(b)
		{
			try
			{
				wait();
			}
			catch(Exception e)
			{
				System.out.println(e.getMessage());
			}
		}

		System.out.println(Thread.currentThread().getName()   " 进行一次侵犯");
		if(!duobi())
		{
			tiggerblood--;
			System.out.println("tigger 的血量为"   tiggerblood);
		}
		else
			System.out.println("tigger 成功进行了一次躲避");
		b = true;
		if(tiggerblood == 0)
		{
			System.out.println("GAME OVER !!!  武松 WIN");
			System.exit(0);
		}
		notify();		
	}
	//老虎侵犯
	public synchronized void hugong()
	{
		if(!b)
		{
			try
			{
				wait();
			}
			catch(Exception e)
			{
				System.out.println(e.getMessage());
			}
		}
		System.out.println(Thread.currentThread().getName()   " 进行一次侵犯");
		if(!duobi())
		{
			wusongblood--;
			System.out.println("武松 的血量为"   wusongblood);
		}
		else
			System.out.println("武松 成功进行了一次躲避");
		b = false;
		if(wusongblood == 0)
		{
				System.out.println("GAME OVER !!!  Tigger WIN");
				System.exit(0);
		}	
		notify();
	}
	public boolean duobi()
	{
		return r.nextBoolean();
	}
}

class Wu implements Runnable
{
	Q q = null;
	public Wu(Q q)
	{
		this.q = q;
	}
	public void run()
	{
		Thread.currentThread().setName("Wusong Thread");
		while(true)
		{
			q.wugong();
		}
	}
	
}
class Hu implements Runnable
{
	Q q = null;
	public Hu(Q q)
	{
		this.q = q; 
	}
	public void run()
	{
		Thread.currentThread().setName("Tigger Thread");
		while(true)
		{
			q.hugong();
		}
	}
}
class Wusong
{
	public static void main(String [] args)
	{
		Q q = new Q();
		Wu wu = new Wu(q);
		Hu hu = new Hu(q);
		new Thread(wu).start();
		new Thread(hu).start();

	}
} http://www.haofapiao.com/linked/20130424.do 
posted @ 2013-04-25 02:39  chinadiy197601  阅读(328)  评论(0编辑  收藏  举报