某公司组织年会,会议入场时有两个入口,在入场时每位员工都能获取一张双色球彩票,
假设公司有100个员工,利用多线程模拟年会入场过程,
并分别统计每个入口入场的人数,以及每个员工拿到的彩票的号码。
线程运行后打印格式如下:
编号为: 2 的员工 从后门 入场! 拿到的双色球彩票号码是: [17, 24, 29, 30, 31, 32, 07]
编号为: 1 的员工 从前门 入场! 拿到的双色球彩票号码是: [06, 11, 14, 22, 29, 32, 15]
//…
从后门入场的员工总共: 13 位员工
从前门入场的员工总共: 87 位员工
解:
我开了一百个线程模拟一百个员工入场,至于双色球的那部分我做简单了,
我用100内的随机6位数取代替,我重点还是想练习多线程。
附上代码:
import java.util.Arrays;
import java.util.Random;
public class Main {
public static void main(String[] args){
Random random = new Random();
Hall hall = new Hall(random);
for(int i=0;i<100;i++) {
hall.test(i+1); //每循环一次相当于一个员工进场
}
try {
Thread.sleep(2000); //为了让统计最后打印,我们等待2S
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("从后门入场的员工总共: "+Hall.cnt+"位员工");
System.out.println("从前门入场的员工总共: "+Hall.count+"位员工");
}
}
class Staff implements Runnable{ //员工
private int id; //编号
private int[] list; //双色球彩票号码
private String str; //前门还是后门
public Staff(int id,int[] list, String str) {
this.id = id;
this.list = list;
this.str = str;
}
@Override
public void run() {
System.out.println("编号为:"+this.id+"的员工 从"+str+"入场! 拿到的双色球彩票号码是:"+Arrays.toString(list));
}
}
class Hall{ //礼堂
static int count = 0; //前
static int cnt = 0; //后
private int id ; //编号
private int[] list; //双色球彩票号码
private String str; //前门还是后门
private Staff staff;
private Random random;
public Hall(Random random) { //进礼堂
this.random = random;
}
public void test(int id) {
this.id = id;
if(random.nextInt()%2==0) { //随机到双数就是前门,反之
str = "前门";
count++;
}else {
str = "后门";
cnt++;
}
staff = new Staff(id,getlist(),str); //new一个员工
new Thread(staff).start();
}
private int[] getlist() { //双色球
list = new int[7];
for(int i=0;i<7;i++)
{
list[i] = random.nextInt(100)+1;
}
return list;
}
}
有好的多线程练习题资源的可以分享给我一点,哈哈。。。