多线程之停车场-Semaphore

Semaphore:停车场
容量是固定的,出一个线程,进一个线程.
 
代码如下:
/**
 * @author jeremy.li
 * @date 2020/11/30
 * @description 停车场
 */
public class SemaphoreTest implements Runnable {

    static Semaphore semaphore = new Semaphore(5);

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 20; i++) {
            SemaphoreTest semaphoreTest = new SemaphoreTest();
            Thread thread = new Thread(semaphoreTest, i + " 号司机");

            thread.start();
        }
    }

    @Override
    public void run() {
        try {
            semaphore.acquire();
            Thread.sleep(2000);
            System.out.println(Thread.currentThread().getName() + ",抢到了车位");
            semaphore.release();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}

  

关键方法:
acquire();
  从信号量获取一个许可,如果无可用许可前将一直阻塞等待,
release();
  释放一个许可

posted @ 2020-11-30 17:22  一入IT岁月催  阅读(193)  评论(0)    收藏  举报