public class Watermelon {
/**
* @param args
*/
public static void main(String[] args) {
new Thread(new Move("张三",'m')).start();//张三,男,以下类似
new Thread(new Move("李四",'m')).start();
new Thread(new Move("小露",'w')).start();
new Thread(new Move("小红",'w')).start();
new Thread(new Move("小兰",'w')).start();
}
}
class Move implements Runnable{
public static int count = 100;//西瓜数量是100
private String name;//记录人名
private char sex;//记录性别
Move(String name, char sex){//定义有参构造方法
this.name = name;
this.sex = sex;
}
public void run() {
while(true){
synchronized (Move.class) {
if(this.count ==0) break;
if(this.sex == 'w'){//性别为女时搬走一个西瓜
System.out.println("女生"+this.name+"搬走1个西瓜,还剩"+--count+"个");
}
if(this.sex == 'm'){//性别为男时
if(this.count == 1){//若只剩一个,搬走一个西瓜
System.out.println("男生"+this.name+"搬走1个西瓜,还剩"+--count+"个");
}
else{//否则搬走两个西瓜
this.count -= 2;
System.out.println("男生"+this.name+"搬走2个西瓜,还剩"+count+"个");
}
}
}
try {
Thread.sleep(1);//为了显示多线程效果,睡眠1毫秒
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
练下手,初学者也不是很熟悉,仅供参考 |