Semaphore,动态增减信号量

【信号量】:

  • 用于控制对某资源访问的同一时间的并发量。

 

【如何获取】:

  • semaphore.tryAcquire(),尝试获取,不阻塞
  • semaphore.acquire(),没信号量可用时,将进行阻塞等

 

【如何释放】:

  • semaphore.release();
  • 线程抛出各种异常,都别忘了在finally中释放信号量;
  • 如果释放的比获取的信号量还多,例如获取了2个,释放了5次,那么当前信号量就动态的增加为5了,要注意。

 

【动态增加】:

  • 多释放几次,就可以达到信号量动态增加的效果了

 

【动态减小】:

  • 信号量本来有这个api的,不过是protected方法,所以我们需要显式继续Semaphore,并重新实现该api,见ResizeableSemaphore类中的reducePermits(int reduction);
  • 举例如下:(该表格有个假设前提,不存在多余的release而产生出新的信号量,即release次数<=acquire次数)
当前信号量A
(A=A1+A2)
占用信号量A1可用信号量A2重新设置信号量B
(B=B1+B2)
当前可用的信号量B1当前待释放的量B2
532300
53210-2
532960



 

package com.jd.las.basic.service;

import java.util.concurrent.Semaphore;

/**
 * 
 * Title: 动态信号量<br>
 * 
 * Description: <br>
 * 
 * Company: <a href=www.jd.com>京东</a><br>
 * 
 * @author <a href=mailto:longzhun@jd.com>龙准</a>
 * 
 * @date 2015年5月26日 下午7:29:42
 */
public class JdSemaphore {

	 /**
     * semaphore starts at 0 capacity; must be set by setMaxPermits before use
     */
    private final ResizeableSemaphore semaphore = new ResizeableSemaphore();
 
    /**
     * how many permits are allowed as governed by this semaphore.
     * Access must be synchronized on this object.
     */
    private int maxPermits = 0;
 
    /**
     * New instances should be configured with setMaxPermits().
     */
    public JdSemaphore() {
        // no op
    }
 
    /*
     * Must be synchronized because the underlying int is not thread safe
     */
    /**
     * Set the max number of permits. Must be greater than zero.
     *
     * Note that if there are more than the new max number of permits currently
     * outstanding, any currently blocking threads or any new threads that start
     * to block after the call will wait until enough permits have been released to
     * have the number of outstanding permits fall below the new maximum. In
     * other words, it does what you probably think it should.
     *
     * @param newMax
     */
    public synchronized void setMaxPermits(int newMax) {
        if (newMax < 1) {
            throw new IllegalArgumentException("Semaphore size must be at least 1,"
                + " was " + newMax);
        }
 
        int delta = newMax - this.maxPermits;
 
        if (delta == 0) {
            return;
        } else if (delta > 0) {
            // new max is higher, so release that many permits
            this.semaphore.release(delta);
        } else {
            delta *= -1;
            // delta < 0.
            // reducePermits needs a positive #, though.
            this.semaphore.reducePermits(delta);
        }
 
        this.maxPermits = newMax;
    }
 
    /**
     * Release a permit back to the semaphore. Make sure not to double-release.
     *
     */
    public void release() {
        this.semaphore.release();
    }
 
    /**
     * Get a permit, blocking if necessary.
     *
     * @throws InterruptedException
     *             if interrupted while waiting for a permit
     */
    public void acquire() throws InterruptedException {
        this.semaphore.acquire();
    }
 
    /**
     * A trivial subclass of <code>Semaphore</code> that exposes the reducePermits
     * call to the parent class. Doug Lea says it's ok...
     * http://osdir.com/ml/java.jsr.166-concurrency/2003-10/msg00042.html
     */
    private static final class ResizeableSemaphore extends Semaphore {
        /**
         *
         */
        private static final long serialVersionUID = 1L;
 
        /**
         * Create a new semaphore with 0 permits.
         */
        ResizeableSemaphore() {
            super(0);
        }
 
        @Override
        protected void reducePermits(int reduction) {
            super.reducePermits(reduction);
        }
    }

}

 

这里可参考:http://blog.teamlazerbeez.com/2009/04/20/javas-semaphore-resizing/

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
my_semaphore是一个信号量,它用于在多任务或多进程环境中,实现对共享资源的互斥访问。信号量是一个计数器,用于控制对共享资源的访问。当一个任务或进程需要访问共享资源时,它会请求信号量,如果信号量计数器的值大于0,该任务或进程就可以访问共享资源,并将信号量计数器减1。如果信号量计数器的值为0,该任务或进程就必须等待,直到有其他任务或进程释放信号量。 在C语言中,可以使用sem_init、sem_wait和sem_post等函数来操作信号量。sem_init函数用于初始化信号量,sem_wait函数用于等待信号量,并将信号量计数器减1,sem_post函数用于释放信号量,并将信号量计数器加1。以下是一个信号量的示例代码: ``` #include <semaphore.h> #include <stdio.h> #include <pthread.h> sem_t my_semaphore; void *my_thread(void *arg) { sem_wait(&my_semaphore); printf("Thread %d is accessing the shared resource.\n", *(int *)arg); sem_post(&my_semaphore); pthread_exit(NULL); } int main() { int i; pthread_t threads[5]; sem_init(&my_semaphore, 0, 1); for (i = 0; i < 5; i++) { pthread_create(&threads[i], NULL, my_thread, (void *)&i); } for (i = 0; i < 5; i++) { pthread_join(threads[i], NULL); } sem_destroy(&my_semaphore); return 0; } ``` 在上面的例子中,我们创建了5个线程,并使用信号量来控制这些线程对于共享资源的访问。由于我们初始化信号量的值为1,因此只有一个线程可以访问共享资源。每个线程在访问共享资源前都会调用sem_wait函数来等待信号量,然后在访问完共享资源后调用sem_post函数来释放信号量。这样可以保证同一时间只有一个线程可以访问共享资源。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值