本帖最后由 水月灬清影 于 2016-8-25 12:54 编辑
感谢 lbx95272006 的指点,把红包资源类的 if 改成 while,notify 改成 notifyAll 可以实现一人一个红包,但是不合题目要求,题目讲的是抢到之后可以再抢,不限次数,所以还需要改进,还有哪位朋友有高见,目前代码如下:
[Java] 纯文本查看 复制代码 import java.util.Random;
//红包资源类
public class Bonus {
private static int count=5;
private static int bonus;
private boolean flag;
public synchronized void set(){
while(this.flag==true){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(count>0){
Random r=new Random();
bonus=r.nextInt(10)+1;
count--;
System.out.println("红包已生成");
}
this.flag=true;
this.notifyAll();
}
public synchronized void get(){
while(this.flag==false){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+bonus+"元");
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.flag=false;
this.notifyAll();
}
}
|