静态锁对象
public class ThreadLock { public static Object obj= new Object();}
API
@RequestMapping("/thread")@RestControllerpublic class ThreadController { @GetMapping("carAccess") public String carAccess(@RequestParam("carNumber") String carNumber) throws InterruptedException { System.out.println("车牌号{"+carNumber+"}正在排队"); synchronized (ThreadLock.obj){ ThreadLock.obj.wait(); } System.out.println("车牌号{"+carNumber+"}已经驶离缴费站"); return null; } @GetMapping("carNotify") public String notifyCar(){ synchronized (ThreadLock.obj){ ThreadLock.obj.notify(); } return null; } @GetMapping("carNotifyAll") public String NotifyAllCar(){ synchronized (ThreadLock.obj){ ThreadLock.obj.notifyAll(); } return null; }}
实验1:请求三次carAccess且携带不同参数,然后请求notify接口
###GET http://localhost:8888/thread/carAccess?carNumber=001###GET http://localhost:8888/thread/carAccess?carNumber=002###GET http://localhost:8888/thread/carAccess?carNumber=003
###GET http://localhost:8888/thread/carNotify
发现请求一次,释放一把锁且安装按照顺序释放锁
实验2:请求三次carAccess且携带不同参数,然后请求notifyAll接口
###GET http://localhost:8888/thread/carNotifyAll
发现一次性释放三把锁且锁的释放顺序有一定的随机性