Java?????Semaphore
???????????? ???????[ 2015/3/13 13:34:33 ] ????????JAVA ??????? Semaphore ??? ???
????Semaphore
????Semaphore????????????????????????????????????????????????á?
????Semaphore????????????????5???????????10?????????????????????ж??????????????????????5?????????????5?????? ???κ??????????????е????????5????????????????????????????????5?????п??????????????????????????????????????????????????????Semaphore??????????????????????????Semaphore??????????????????????????????????????????“??”?????????????????“??”????????????????????Щ?????
????????????????????????????????????????????????????λ????????????λ??????????????????????????????????????????????????譚??????????3???????μ??????????????????????????????ò??????????????????????????????????????????????????????????????????????????????????????????????????
?????????????????У???λ??????????????????????????????????????????????á?
???????????????????????????£??????????????????????λ?????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????? Wait??????? ?? Release???????? ???????????Wait???????????????????????????????????????????????????????????????Release????????????????????????м????????????????????????ò???????????“???”???????????????????????????????????????
????Semaphore(int permits?? boolean fair)
????//???????и????????????????????????Semaphore??
?????????????????????????ù??????????????????У?????????????????FIFO????У???????????????????????п?????????е??????
???????
????Semaphore??????????????????????????????? acquire() ???????????????е?????? release() ????????ɡ?
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
public class SemaphoreTest {
public static void main(String[] args) {
// ????
ExecutorService exec = Executors.newCachedThreadPool();
// ???5???????????
final Semaphore semp = new Semaphore(5);
// ???20??????????
for (int index = 0; index < 50; index++) {
final int NO = index;
Runnable run = new Runnable() {
public void run() {
try {
// ??????
semp.acquire();
System.out.println("Accessing: " + NO);
Thread.sleep((long) (Math.random() * 10000));
// ??????????
semp.release();
//availablePermits()???????????????ж????????????
System.out.println("-----------------" + semp.availablePermits());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
exec.execute(run);
}
??????
???·???
??????????????????
2023/3/23 14:23:39???д?ò??????????
2023/3/22 16:17:39????????????????????Щ??
2022/6/14 16:14:27??????????????????????????
2021/10/18 15:37:44???????????????
2021/9/17 15:19:29???·???????·
2021/9/14 15:42:25?????????????
2021/5/28 17:25:47??????APP??????????
2021/5/8 17:01:11