您的位置:首页 > 其它

使用thread类

2015-10-23 15:44 302 查看
package thread;

public class Example_1 {
	public static void main(String args[]){
		Home home=new Home();
		Thread dog,cat;
		home.setFood(20);
		cat=new Thread(home);
		dog=new Thread(home);
		dog.setName("狗");
		cat.setName("猫");
		cat.start();
		dog.start();
	}
}
class Home implements Runnable{
	int foodAmount;
	public void setFood(int w){
		foodAmount=w;
	}
	public void run(){
		while(true){
			String name=Thread.currentThread().getName();
			if(name.equals("狗")){
				System.out.println(name+"吃饭");
				foodAmount-=2;
			}
			else if(name.equals("猫")){
				System.out.println(name+"吃饭");
				foodAmount-=1;
			}
			System.out.println(" 剩 "+foodAmount);
			try{
				Thread.sleep(2000);
			}
			catch(InterruptedException e){}
			if(foodAmount<=0)
				return ;
		}
	}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: