[AppleScript] 纯文本查看 复制代码 package com.gfxy.thread;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.TreeSet;
public class Test1 {
/**
* 7、某公司组织年会,会议入场时有两个入口,在入场时每位员工都能获取一张双色球彩票,假设公司有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) {
Door d = new Door();
Thread t1 = new Thread(d,"前门");
Thread t2 = new Thread(d,"后门");
t1.start();
t2.start();
}
}
class Door implements Runnable {
private static int peoples = 100;
private static int front = 0;
private static int back = 0;
@Override
public void run() {
while(true) {
synchronized (Door.class) {
String name = Thread.currentThread().getName();
if (peoples <= 0) {
break;
}
if("前门".endsWith(name)) {
front++;
} else {
back++;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("编号为: " + peoples-- + " 的员工 从"
+ name + "入场!拿到的双色球彩票号码是:"+getCaiPiao());
}
}
if("前门".equals(Thread.currentThread().getName())){
System.out.println("从后门入场的员工总共: " + front + " 位员工");
System.out.println("从后门入场的员工总共: " + back +"位员工");
}
}
public List<String> getCaiPiao() {
List<String> list = new ArrayList<String>();
TreeSet<String> ts = new TreeSet<String>();
Random r = new Random();
while(ts.size() < 6) {
int red = r.nextInt(33) + 1;
if(red < 10){
ts.add("0" +red);
} else {
ts.add(red+"");
}
}
list.addAll(ts);
int blue = r.nextInt(16) + 1;
if(blue > 10){
list.add(blue+"");
} else {
list.add("0" + blue);
}
return list;
}
}
希望对你有用
|