场景:公司有若干部门,每个部门一个厕所,每个部门的员工争抢本部门的厕所
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
/**
* @comments 测试main入口
* 场景:公司有若干部门,每个部门一个厕所,每个部门的员工争抢本部门的厕所
* @author Bruce
* @date 2017年11月24日
*/
public class ToiletTester {
//总人数
private static final int personNum = 30;
//所有部门的厕所
public static Map<Integer, Toilet> DepToilets = new ConcurrentHashMap<>();
public static void main(String[] args) {
for (int i = 1; i <= personNum; i++) {
int depId = randomRange(5, 1);//为员工随机分配部门id(从1到5)
String empName = fixedLengthFill0(3, i) + " 号员工";
Person person = new Person(depId, empName);
person.start();
}
}
//------------- 工具方法 ------------------------------
public static Integer randomRange(int max, int min) {
return new Random().nextInt(max)%(max-min+1) + min;
}
private static String fixedLengthFill0(int length, int seq) {
StringBuilder strBu = new StringBuilder();
int fillLen = length - String.valueOf(seq).length();
for (int i = 0; i < fillLen; i++) {
strBu.append("0");
}
strBu.append(seq);
return strBu.toString();
}
}
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @comments 执行的业务方法(被调用的)
* @author Bruce
* @date 2017年11月24日
*/
public class Toilet {
private Integer depId;
private Lock lock = new ReentrantLock(true);
public Toilet(Integer depId) {
this.depId = depId;
}
public void enter() {
try {
lock.lock();//拿到锁(锁门)
System.out.println(Thread.currentThread().getName() + "获得Toilet-DEP"+depId+" 使用权,time:" + System.currentTimeMillis());
int sec = ToiletTester.randomRange(3, 1);
Thread.sleep(sec * 1000);//使用1-3秒
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();//释放锁(完事了,开门出去)
}
}
//-------------- get & set methods -----------
public Integer getDepId() {
return depId;
}
public void setDepId(Integer depId) {
this.depId = depId;
}
public Lock getLock() {
return lock;
}
}
/**
* @comments 业务调用者
* @author Bruce
* @date 2017年11月24日
*/
public class Person extends Thread{
private Integer depId;//部门id
private String empName;//员工姓名
public Person(Integer depId, String empName) {
this.setName("DEP" + depId + "-" + empName);
this.depId = depId;
this.empName = empName;
}
@Override
public void run() {
//如果没有厕所就建立个部门厕所
ToiletTester.DepToilets.putIfAbsent(depId, new Toilet(depId));
//员工根据所在部门id找到部门的厕所
Toilet toilet = ToiletTester.DepToilets.get(depId);
toilet.enter();//进入
super.run();
}
//-------------- get & set methods ---------------------------
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public Integer getDepId() {
return depId;
}
public void setDepId(Integer depId) {
this.depId = depId;
}
}