[Java] 纯文本查看 复制代码 import java.util.HashSet;
import java.util.Iterator;
/**
*
* 7、有一组奖品:{macBookPro:8988?,三星note7:5695?,小米4:2688?,联想P612:866?,iphone7:5688?}(
* 每个奖品只有一个,并且同一时间只能有一个人抽奖);开启两个线程A、B模拟两个人抽奖的过程(每个人抽取的次数不做限制),直到奖品抽完为止,
* 打印出每个人抽到的奖品和价值金额;
*
*/
class Prize {
public String name;
public Integer price;
public Prize(String name, Integer price) {
super();
this.name = name;
this.price = price;
}
@Override
public String toString() {
return "Prize [name=" + name + ", price=" + price + "]";
}
}
class MyThread extends Thread {
private HashSet<Prize> hashSet;
public MyThread(HashSet<Prize> hashSet) {
this.hashSet = hashSet;
}
@Override
public void run() {
while (true) {
synchronized (Thread.class) {
Iterator<Prize> iterator = hashSet.iterator();
if (iterator.hasNext()) {
Prize string = iterator.next();
System.out.println(this.getName() + string);
iterator.remove();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
break;
}
}
}
}
}
public class Test00 {
public static HashSet<Prize> hashSet = new HashSet<Prize>();
public static void main(String[] args) {
hashSet.add(new Prize("macBookPro", 8988));
hashSet.add(new Prize("三星note7", 5695));
hashSet.add(new Prize("小米4", 2688));
hashSet.add(new Prize("联想P612", 866));
hashSet.add(new Prize("iphone7", 5688));
MyThread myThread1 = new MyThread(hashSet);
MyThread myThread2 = new MyThread(hashSet);
myThread1.setName("张三 ");
myThread2.setName("李四 ");
myThread1.start();
myThread2.start();
}
} |