package com.heima.multithreading;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Test013 {
/*
* 有一个抽奖池,该抽奖池中存放了奖励的金额,该抽奖池用一个数组int[] arr = {10,5,20,50,100,200,500,800,2,80,300};
创建两个抽奖箱(线程)设置线程名称分别为“抽奖箱1”,“抽奖箱2”,随机从arr数组中获取奖项元素并打印在控制台上,格式如下:
抽奖箱1 又产生了一个 10 元大奖
抽奖箱2 又产生了一个 100 元大奖
数组的 每一个数字只能出现一次
*/
public static void main(String[] args) {
Lottery ly = new Lottery();
Thread t1 = new Thread(ly);
Thread t2 = new Thread(ly);
t1.setName("抽奖箱1");
t2.setName("抽奖箱2");
t1.start();
t2.start();
}
}
class Lottery implements Runnable {
List<Integer> list = getList();
@Override
public void run() {
while(true){
synchronized (this) {
if(list.size() > 0){
System.out.println(Thread.currentThread().getName() + "又产生了一个 " + list.get(0) + " 元大奖 ");
list.remove(0);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
break;
}
}
}
}
private List<Integer> getList() {
int[] arr = {10,5,20,50,100,200,500,800,2,80,300};
List<Integer> list = new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
list.add(arr[i]);
}
Collections.shuffle(list);
return list;
}
} |