package day27;
import java.util.ArrayList;
import java.util.Random;
/*
* 有一个抽奖池,该抽奖池中存放了奖励的金额,该抽奖池用一个数组int[] arr = {10,5,20,50,100,200,500,800,2,80,300};
创建两个抽奖箱(线程)设置线程名称分别为“抽奖箱1”,“抽奖箱2”,随机从arr数组中获取奖项元素并打印在控制台上,格式如下:
抽奖箱1 又产生了一个 10 元大奖
抽奖箱2 又产生了一个 100 元大奖
*/
public class demo1 {
public static void main(String[] args) {
arr a = new arr();
Thread t = new Thread(a);
Thread t1 = new Thread(a);
t.setName("抽奖箱1");
t1.setName("抽奖箱2");
t.start();
t1.start();
}
}
class arr implements Runnable {
int[] arr = { 10, 5, 20, 50, 100, 200, 500, 800, 2, 80, 300 };
ArrayList list = new ArrayList<>();
Random ran = new Random();
public void run() {
while (true) {
/* System.out.println(Thread.currentThread().getName()); */
/*synchronized (arr.class) {*/
if (arr.length == list.size()) {
System.out.println(list);
return;
}
if (list.size() > arr.length) {
return;
}
if (list.size() < arr.length) {
int nextInt = ran.nextInt(arr.length);
if (!list.contains(arr[nextInt])) {
System.out.println("==" + arr[nextInt]);
list.add(arr[nextInt]);
// System.out.println(arr[nextInt]);
// System.out.println(list);
System.out.println(Thread.currentThread().getName() + "又产生了" + arr[nextInt] + "元大奖" + nextInt);
// }
}
}
}
}
}
|
|