[英]Using Semaphores in java and storing into array
I am new to using semaphores, so bear with me please.我是使用信号量的新手,所以请耐心等待。 So, lets say I have 7 permits to give out and 49 people(threads) in total are waiting for them.
所以,假设我有 7 个许可证要发放,总共有 49 个人(线程)在等待它们。 If I acquire() the semaphores for the first 7 people and store them into a list array(store the semaphores of people) for instance by passing them into another class.
如果我获取()前 7 个人的信号量并将它们存储到列表数组中(存储人的信号量),例如通过将它们传递到另一个类。 Then if I go back into that array and loop through and release() the semaphores within that other class, shouldn't that then trigger the other threads waiting to take that next key?
然后,如果我回到该数组并循环并释放()该其他类中的信号量,那不应该触发其他线程等待获取下一个键吗? Because what I just coded did this and the next 7 threads don't acquire the key.
因为我刚刚编写的代码做到了这一点,接下来的 7 个线程没有获取密钥。 I didn't post the code because I just want to conceptually understand what I am missing out on, and then implement it.
我没有发布代码,因为我只是想从概念上了解我错过了什么,然后实现它。
If what you want is to have max 7 threads to be active at one time, you only need 1 semaphore, like this:如果您想要一次最多有 7 个线程处于活动状态,则只需要 1 个信号量,如下所示:
Semaphore available = new Semaphore(7, true);
and let each of your threads call available.acquire() (and eventually available.release() ), against this very semaphore instance (shared by all the threads), and that is it.让您的每一个线程呼叫available.acquire()(最终available.release()),对这个非常旗语实例(由所有线程共享),那就是它。
Here is what java.util.concurrent.Semaphore javadoc says:这是 java.util.concurrent.Semaphore javadoc 所说的:
A counting semaphore.
计数信号量。 Conceptually, a semaphore maintains a set of permits.
从概念上讲,信号量维护一组许可。 Each acquire() blocks if necessary until a permit is available, and then takes it.
如有必要,每个acquire() 都会阻塞,直到获得许可为止,然后获取它。 Each release() adds a permit, potentially releasing a blocking acquirer.
每个 release() 添加一个许可,可能会释放一个阻塞的获取者。 However, no actual permit objects are used;
但是,没有使用实际的许可对象; the Semaphore just keeps a count of the number available and acts accordingly.
信号量只是计算可用的数量并相应地采取行动。
If you're acquiring a semaphore, be sure to release it at some point as well.如果您正在获取信号量,请务必在某个时候释放它。 ex Pseudo code:
前伪代码:
sem = Semaphore.new(2, true)
Thread1 {
sem.acquire()
// Do something
sem.release()
};
Thread2 {
sem.acquire()
// Do something
sem.release()
}
Thread3 {
//blocked until one of the first two Thread releases.
sem.acquire()
// Do something
sem.release()
}
This is adding to zeppelin's point...这增加了齐柏林飞艇的观点......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.