package cn.itcast.test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class Test014 {
/**
* @param args
*
.某公司组织年会,会议入场时有两个入口,在入场时每位员工都能获取一张双色球彩票,假设公司有100个员工,利用多线程模拟年会入场过程,
并分别统计每个入口入场的人数,以及每个员工拿到的彩票的号码。线程运行后打印格式如下:
编号为: 2 的员工 从后门 入场! 拿到的双色球彩票号码是: [17, 24, 29, 30, 31, 32, 07]
编号为: 1 的员工 从后门 入场! 拿到的双色球彩票号码是: [06, 11, 14, 22, 29, 32, 15]
//.....
从后门入场的员工总共: 13 位员工
从前门入场的员工总共: 87 位员工
*/
public static void main(String[] args) {
//获得彩票号码
Entrance et = new Entrance();
new Thread(et,"前门").start();
new Thread(et,"后门").start();
try {
Thread.sleep(20000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("从后门入场的员工总共: " + et.getFrontDoor() + "位员工");
System.out.println("从前门入场的员工总共: " + et.getBackDoor() + "位员工");
}
}
class Entrance implements Runnable {
static List<ArrayList<Integer>> list = getLlist();
private int number = 100;
private static int frontDoor = 0;
private static int backDoor = 0;
@Override
public void run() {
while(true){
synchronized (this) {
if(number > 0){
System.out.println("编号为: " + number-- + " 的员工 从" + Thread.currentThread().getName() + " 入场! 拿到的双色球彩票号码是: " + list.get(0));
list.remove(0);
if("前门".equals(Thread.currentThread().getName())){
frontDoor++;
}else{
backDoor++;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
break;
}
}
}
}
public static List<ArrayList<Integer>> getLlist() {
List<ArrayList<Integer>> llist = new ArrayList<ArrayList<Integer>>();
while(llist.size() < 101){
ArrayList<Integer> list = getList();
if(!llist.contains(list)){
llist.add(list);
}
}
return llist;
}
private static ArrayList<Integer> getList() {
ArrayList<Integer> list = new ArrayList<Integer>();
Random rd = new Random();
while(list.size() <= 6){
int i = rd.nextInt(33) + 1;
if(!list.contains(i)){
list.add(i);
}
}
Collections.sort(list);
list.add(rd.nextInt(16) + 1);
return list;
}
public static int getFrontDoor() {
return frontDoor;
}
public static int getBackDoor() {
return backDoor;
}
} |