Эх сурвалжийг харах

商家被预约接口微调

liude 1 жил өмнө
parent
commit
f597ce2b09

+ 40 - 0
src/main/java/com/chelvc/cloud/admin/controller/SemaphoreTest.java

@@ -0,0 +1,40 @@
+package com.chelvc.cloud.admin.controller;
+
+import java.util.concurrent.Semaphore;
+
+public class SemaphoreTest {
+
+    private static Semaphore semaphore = new Semaphore(1);
+
+    public Semaphore getSemaphore() {
+        return semaphore;
+    }
+    public static void main(String[] args) {
+        // 模拟15辆车同时停车
+        for (int i = 0; i < 15; i++) {
+            Thread thread = new Thread(new Runnable() {
+                @Override
+                public void run() {
+                    try {
+                        System.out.println("=====" + Thread.currentThread().getName() + "车辆来到停车场");
+                        if (semaphore.availablePermits() == 0) {
+                            // 没有车位了
+                            System.out.println("车位不足,请耐心等待," + Thread.currentThread().getName() + "车辆正在等待");
+                        }
+                        // 获取车位停车
+                        semaphore.acquire();
+                        System.out.println(Thread.currentThread().getName()+"成功进入停车场");
+                        //模拟车辆在停车场停留的时间
+                        Thread.sleep(3000);
+                        //驶出停车场
+                        semaphore.release();
+                        System.out.println(Thread.currentThread().getName()+"驶出停车场");
+                    } catch (InterruptedException e) {
+                        e.printStackTrace();
+                    }
+                }
+            });
+            thread.start();
+        }
+    }
+}