package 黑马面试题;
import java.util.Random;
/**
* 模拟抢红包过程,生成5个红包(金额是随机生成的,范围在1-10元之间)
* 创建5个线程代表5个人,然后让这5个人去抢这5个红包,每次抢红包需要300ms的时间,
* 在控制台打印出 (xxx抢了xxx元)
* (不限定每人抢的次数并且抢到红包后还可以接着抢,每次生成一个红包)(10分)
*
* @author mars
*
*/
public class TestQiangHongBao{
public static void main(String[] args) {
Qiang q= new Qiang();
Thread t1 = new Thread(q);
t1.setName("1号");
Thread t2 = new Thread(q);
t2.setName("2号");
Thread t3 = new Thread(q);
t3.setName("3号");
Thread t4 = new Thread(q);
t4.setName("4号");
Thread t5 = new Thread(q);
t5.setName("5号");
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
}
class Qiang implements Runnable {
private int hb=5 ;
@Override
public void run() {
Random r = new Random();
while(hb!=0){
hb--;
int i = r.nextInt(10) + 1;
System.out.println(Thread.currentThread().getName() + "抢了" + i + "元");
}
try {
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
|