附上代码--------
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
/**
* @author KanYouKyou
* 2.模拟抢红包过程,生成5个红包(金额是随机生成的,范围在1-10元之间)创建5个线程代表5个人,然后让这5个人去抢这5个红包
* 每次抢红包需要300ms的时间, 在控制台打印出 (xxx抢了xxx元)
* (每次生成一个红包,不限定每人抢的次数并且抢到红包后还可以接着抢,)(10分)
*/
public class Hongbao {
// 红包类,人(具有抢红包的功能)
public static void main(String[] args) {
Person p1 = new Person("赵日天");
Person p2 = new Person("叶良辰");
Person p3 = new Person("冯佳");
Person p4 = new Person("kyou");
Person p5 = new Person(" 龙傲天");
p1.start();
p2.start();
p3.start();
p4.start();
p5.start();
}
}
class Person extends Thread {
public static Integer[] son = { 1, 2, 3, 4, 5 };
public static ArrayList<Integer> bag = new ArrayList<>(Arrays.asList(son));
public Person(String name) {
super(name);
}
public void run() {
try {
Thread.sleep(300);
synchronized (getClass()) {
if (bag.size() > 0) {
Collections.shuffle(bag);
System.out.println(getName() + "抢到了"+bag.get(bag.size() - 1)+"号"+new Bag());
;
bag.remove(bag.size() - 1);
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} |