zoukankan      html  css  js  c++  java
  • java中的信号量Semaphore

    Semaphore(信号量)充当了操作系统概念下的“信号量”。它提供了“临界区中可用资源信号量”的相同功能。
    以一个停车场运作为例。为了简单起见,假设停车场只有三个车位,一开始三个车位都是空的。这时如果同时来了五辆车,看门人允许其中三辆不受阻碍的进入,然后放下车拦,剩下的车则必须在入口等待,此后来的车也都不得不在入口处等待。这时,有一辆车离开停车场,看门人得知后,打开车拦,放入一辆,如果又离开两辆,则又可以放入两辆,如此往复。

    在这个停车场系统中,车位是公共资源(临界区资源),每辆车好比一个线程,看门人起的就是信号量的作用。

    更进一步,信号量的特性如下:信号量是一个非负整数(车位数),所有通过它的线程(车辆)都会将该整数减一(通过它当然是为了使用资源),当该整数值为零时,所有试图通过它的线程都将处于等待状态。在信号量上我们定义两种操作: acquire(获取资源) 和 Release(释放资源)。 当一个线程调用acquire(获取资源)操作时,它要么通过然后将信号量减一,要么一直等下去,直到信号量大于一或超时。Release(释放)实际上是在信号量上执行加操作,对应于车辆离开停车场,该操作之所以叫做“释放”是因为加操作实际上是释放了由信号量守护的资源。

    package com.lt.thread.SamephoreTest;
    import java.util.concurrent.Semaphore;
    /**
     * Created by ltao on 2015-2-9.
     */
    public class Parking implements Runnable {
        private int count;
        private Semaphore semaphore;
        public int getCount() {
            return count;
        }
        public void setCount(int count) {
            this.count = count;
        }
        public Semaphore getSemaphore() {
            return semaphore;
        }
        public void setSemaphore(Semaphore semaphore) {
            this.semaphore = semaphore;
        }
        public Parking(int count)
        {
            this.count=count;
            this.semaphore=new Semaphore(count);
        }
        public void parking()
        {
            try {
                semaphore.acquire();
                try {
                    Thread.sleep(100);
                    System.out.println(Thread.currentThread().getName()+" find a paking space");
                }
               catch (InterruptedException e)
               {
                   e.printStackTrace();
               }
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            finally {
                System.out.println(Thread.currentThread().getName()+" release a paking space");
                semaphore.release();
            }
        }
        @Override
        public void run()
        {
            this.parking();
        }
        public static void main(String[] args)
        {
            Parking parking=new Parking(5);
            Thread[] threads=new Thread[13];
            for (int i=0;i<threads.length;i++)
            {
                threads[i]=new Thread(parking,"thread"+i);
            }
            for (int i=0;i<threads.length;i++)
            {
                threads[i].start();
            }
        }
    }
  • 相关阅读:
    samba
    sed用法
    Jenkins流水线项目发布流程
    Jenkins
    CI/CD
    tomcat
    gitlab
    rsync
    HAPROXY
    基于LVS的web集群部署(http)
  • 原文地址:https://www.cnblogs.com/limingluzhu/p/4325999.html
Copyright © 2011-2022 走看看