public static void main(String[] args) {
Employee e = new Employee();
Thread t1 = new Thread(e);
Thread t2 = new Thread(e);
t1.start();
t2.start();
}
}
class Employee implements Runnable{
static int emp = 100;
int num = 1;
int[] arrNum;
LinkedHashSet<Integer> hs = new LinkedHashSet<Integer>();
HashMap<String, Integer> hm = new HashMap<>();
String[] door = {"前门","后门"};
Random rd = new Random();
@Override
public void run() {
while(emp > 0){
synchronized (this) {
while(hs.size() < 6){
hs.add(rd.nextInt(33)+1);
}
hs.add(rd.nextInt(16)+1);
String getDoor = door[rd.nextInt(2)];
if(getDoor.equals("前门")){
if(!hm.containsKey(getDoor)){
hm.put(getDoor, 1);
}else{
hm.put(getDoor, hm.get(getDoor)+1);
}
System.out.println("编号为:" + num + "的员工从" + getDoor + "入场! 拿到的双色球彩票号码是: " + hs);
}else if(getDoor.equals("后门")){
if(!hm.containsKey(getDoor)){
hm.put(getDoor, 1);
}else{
hm.put(getDoor, hm.get(getDoor)+1);
}
System.out.println("编号为:" + num + "的员工从" + getDoor + "入场! 拿到的双色球彩票号码是: " + hs);
}
emp--;
num++;
hs.clear();
}
}
// System.out.println("前门" + "..." + hm.get("前门"));
// System.out.println("后门" + "..." + hm.get("后门"));
}
}
这样的结果是
编号为:1
*
*
*
编号为:96的员工从后门入场! 拿到的双色球彩票号码是: [7, 30, 28, 11, 24, 10, 2]
编号为:97的员工从前门入场! 拿到的双色球彩票号码是: [11, 9, 28, 14, 6, 16, 5]
编号为:98的员工从后门入场! 拿到的双色球彩票号码是: [16, 21, 20, 15, 26, 23, 4]
编号为:99的员工从后门入场! 拿到的双色球彩票号码是: [24, 22, 23, 29, 30, 12, 1]
编号为:100的员工从后门入场! 拿到的双色球彩票号码是: [3, 7, 4, 1, 24, 8, 13]
编号为:101的员工从前门入场! 拿到的双色球彩票号码是: [13, 17, 28, 26, 19, 14, 4]
而如果我把run方法中的while(emp>0)换成while(true)来做,结果又不一样
public static void main(String[] args) {
Person p = new Person();
Thread t1 = new Thread(p);
Thread t2 = new Thread(p);
t1.start();
t2.start();
}
}
class Person implements Runnable{
static int emp = 100;
int num = 1;
int[] arrNum;
LinkedHashSet<Integer> hs = new LinkedHashSet<Integer>();
HashMap<String, Integer> hm = new HashMap<>();
String[] door = {"前门","后门"};
Random rd = new Random();
@Override
public void run() {
while(true){
synchronized (this) {
if(emp > 0){
while(hs.size() < 6){
hs.add(rd.nextInt(33)+1);
}
hs.add(rd.nextInt(16)+1);
String getDoor = door[rd.nextInt(2)];
if(getDoor.equals("前门")){
if(!hm.containsKey(getDoor)){
hm.put(getDoor, 1);
}else{
hm.put(getDoor, hm.get(getDoor)+1);
}
System.out.println("编号为:" + num + "的员工从" + getDoor + "入场! 拿到的双色球彩票号码是: " + hs);
}else if(getDoor.equals("后门")){
if(!hm.containsKey(getDoor)){
hm.put(getDoor, 1);
}else{
hm.put(getDoor, hm.get(getDoor)+1);
}
System.out.println("编号为:" + num + "的员工从" + getDoor + "入场! 拿到的双色球彩票号码是: " + hs);
}
// if(num == 100){
// System.out.println("前门" + "..." + hm.get("前门"));
// System.out.println("后门" + "..." + hm.get("后门"));
// return;
// }
emp--;
num++;
hs.clear();
}
}
}
}
}
结果是
编号为:97的员工从前门入场! 拿到的双色球彩票号码是: [6, 13, 30, 16, 8, 26, 2]
编号为:98的员工从前门入场! 拿到的双色球彩票号码是: [32, 19, 12, 4, 2, 6, 10]
编号为:99的员工从后门入场! 拿到的双色球彩票号码是: [8, 12, 17, 24, 26, 25, 1]
编号为:100的员工从前门入场! 拿到的双色球彩票号码是: [30, 28, 12, 1, 18, 25, 4]
为什么会不一样啊 啊啊啊啊 啊
|
|