public class TestDemo { public static void main(String[] args) { //1.现有一个数组装了10个奖品在里面. String[] box = {"电视机","电冰箱","电脑","游戏机","洗衣机","空调","手机","平板电脑","电动车","电饭煲"}; //2.转换为List集合 Listlist = new ArrayList<>(Arrays.asList(box)); //3.创建三个线程, 并把"奖池"传入到线程中 MyThread mt1 = new MyThread(list); MyThread mt2 = new MyThread(list); MyThread mt3 = new MyThread(list); mt1.setName("张三"); mt2.setName("李四"); mt3.setName("王五"); //4.启动三个线程. mt1.start(); mt2.start(); mt3.start(); } } ============================================================= public class MyThread extends Thread { //定义List集合,用来存储所有的奖品 private List list; public MyThread(List list) { this.list = list; } //定义List集合,存储自己抽到的奖品(因为是成员变量,所以每个MyThread对象,都有一个自己的集合) private List myList = new ArrayList<>(); @Override public void run() { while (true) { synchronized (MyThread.class) { //获取集合中还有多少奖品 int size = list.size(); if (size > 0) { //如果还有,就继续抽奖 int index = new Random().nextInt(size); //删除的同时,可以把被删除元素返回,相当于拿出来了 String str = list.remove(index); myList.add(str); } else { //如果,没有就打印,并输出 System.out.println(getName() + ":" + myList); break; } } } } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)