模拟高并发武将穿装备

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);
		}
	}
	
	
	
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值