题目:
某公司组织年会,会议入场时有两个入口,在入场时每位员工都能获取一张双色球彩票,假设公司有100个员工,利用多线程模拟年会入场过程,并分别统计每个入口入场的人数,以及每个员工拿到的彩票的号码。线程运行后打印格式如下:
编号为: 2 的员工 从后门 入场! 拿到的双色球彩票号码是: [17, 24, 29, 30, 31, 32, 07]
编号为: 1 的员工 从后门 入场! 拿到的双色球彩票号码是: [06, 11, 14, 22, 29, 32, 15]
//.....
从后门入场的员工总共: 13 位员工
从前门入场的员工总共: 87 位员工
分析:
1.要想实现这个程序,首先需要定义一个资源类,用来存放编号;设置一个字符串变量 用来存放双色球的信息(为什么没有用int类型:因为int类型我没搞明白如何在小于10的数字之中把0给添加上…);
class Resource {
public int number = 1;
String s;
}
2.创建两个线程实现前门和后门员工进入信息的打印。
class Thread1 implements Runnable {
int headNum = 0;
private Resource r;
public Thread1(Resource r) {
this.r = r;
}
@Override
public void run() {
ArrayList<String> arr = new ArrayList<>();
while (true) {
synchronized (r) {
if (r.number < 101) {
new ShuangSeQiouDemo().ShuangSeQiou(r, arr);
System.out.println("编号为" + r.number++ + "的员工从后门入场!" + "拿到的双色球彩票号码是:"
+ Arrays.toString(arr.toArray()));
arr.clear();
headNum++;
} else {
break;
}
}
}
}
}
class Thread2 implements Runnable {
int afterNum = 0;
private Resource r;
public Thread2(Resource r) {
this.r = r;
}
@Override
public void run() {
ArrayList<String> arr = new ArrayList<>();
while (true) {
synchronized (r) {
if (r.number < 101) {
Random ran = new Random();
new ShuangSeQiouDemo().ShuangSeQiou(r, arr);
System.out.println("编号为" + r.number++ + "的员工从前门入场!" + "拿到的双色球彩票号码是:"
+ Arrays.toString(arr.toArray()));
arr.clear();
afterNum++;
} else {
break;
}
}
}
}
}
注意:
这里的new ShuangSeQiouDemo().ShuangSeQiou(r,arr) 是第三步创建的类里面的方法;Arrays.toString(arr.toArray());是打印集合里面所有元素的一种方法;arr.clear();是为了清除每次往集合里面添加的双色球信息。
3.创建实现双色球的类和方法
class ShuangSeQiouDemo {
public static void ShuangSeQiou(Resource r, ArrayList<String> arr) {
Random ran = new Random();
for (int i = 0; i < 6; i++) {
int num = ran.nextInt(32) ;
if (num < 10) {
r.s = "0" + num;
} else {
r.s = num + "";
}
arr.add(r.s);
}
}
}
注意:
这里是我采用获取for循环遍历六次获取六次0-32之间的数字。(会不符合实际…)
4.创建main方法类,实现多线程。
public class Test1 {
public static void main(String[] args) {
Resource r = new Resource();
Thread1 thread1 = new Thread1(r);
Thread2 thread2 = new Thread2(r);
Thread t0 = new Thread(thread1);
Thread t1 = new Thread(thread2);
t0.start();
t1.start();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
printAll(thread1, thread2);
}
public static void printAll(Thread1 t1, Thread2 t2) {
System.out.println("从前门进场的员工总共:" + t1.headNum);
System.out.println("从后门进场的员工总共:" + t2.afterNum);
}
}
总结:
多线程操作一定要注意锁是不是同一把锁…