package bag;
import java.util.HashMap;
public class Equipment {
static HashMap<Integer, Integer> peopleMap=new HashMap<>();
static HashMap<Integer, Integer> equipMap=new HashMap<>();
static{
peopleMap.put(1,0);
peopleMap.put(2,0);
equipMap.put(100, 0);
equipMap.put(200, 0);
}
public static void printInfo(){
for (Integer key : peopleMap.keySet()) {
System.out.println("用户 "+key+" 用户装备 "+peopleMap.get(key));
}
for (Integer key : equipMap.keySet()) {
System.out.println("装备 "+key+" 装备情况 "+equipMap.get(key));
}
}
public static void main(String[] args) {
final int pid1=1;
final int pid2=2;
final int equipId=100;
new Thread(new Runnable() {
@Override
public void run() {
dress(equipId,pid1);
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
dress(equipId,pid2);
}
}).start();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
printInfo();
}
public static void dress(Integer equipId,int pid){
synchronized (equipId) {
int flag=equipMap.get(equipId);
if(flag==1){
System.out.println("装备已经被穿");
return;
}
if(!peopleMap.containsKey(pid)){
System.out.println("用户不存在");
return;
}
if(peopleMap.get(pid)!=0){
System.out.println("用户已经有装备了");
return;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
equipMap.put(equipId, 1);
peopleMap.put(pid, equipId);
}
}
}
08-17
573
09-26