package cn.itcast.ZuoYe;
/*
* 某公司组织年会,会议入场时有两个入口,在入场时每位员工都能获取一张双色球彩票,假设公司有100个员工,利用多线程模拟年会入场过程,
并分别统计每个入口入场的人数,以及每个员工拿到的彩票的号码。线程运行后打印格式如下:
编号为: 2 的员工 从后门 入场! 拿到的双色球彩票号码是: [17, 24, 29, 30, 31, 32, 07]
编号为: 1 的员工 从后门 入场! 拿到的双色球彩票号码是: [06, 11, 14, 22, 29, 32, 15]
//.....
从后门入场的员工总共: 13 位员工
从前门入场的员工总共: 87 位员工
*/
public class Test2 {
public static void main(String[] args) {
final MyRunable m = new MyRunable();
new Thread("前门") {
public void run() {
try {
m.print1();
} catch (InterruptedException e) {
e.printStackTrace();
}
};
}.start();
new Thread("后门") {
public void run() {
try {
m.print2();
} catch (InterruptedException e) {
e.printStackTrace();
}
};
}.start();
}
}
*************************************************************************
public class MyRunable implements Runnable {
Random r = new Random();
public static int a = 1, b = 1, c = 14, d = 0;
public void print1() throws InterruptedException {
synchronized (this) {
while (a <= 100) {
ArrayList<Integer> list = new ArrayList<Integer>();
while (list.size() < 7) {
list.add(r.nextInt(32) + 1);
}
System.out.println("编号为: " + a++ + " 的员工 从" + Thread.currentThread().getName() + " 入场! 拿到的双色球彩票号码是: " + list + " " + c++);
}
}
}
public void print2() throws InterruptedException {
synchronized (this) {
while (a <= 32) {
if (b < 14) {
ArrayList<Integer> list = new ArrayList<Integer>();
while (list.size() < 7) {
list.add(r.nextInt(32) + 1);
}
System.out.println("编号为: " + a++ + " 的员工 从" + Thread.currentThread().getName() + "入场! 拿到的双色球彩票号码是: " + list + "......" + b++);
}
}
}
}
@Override
public void run() {
}
}
|
|