Semaphore信号量
最多允许N个线程同时执行,如果信号量的许可设置为1与ReentrantLock效果一致。
以下示例重点是Semaphore的基本使用,忽略CountDownLatch。
package java_test;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
public class MySemaphore {
static int count = 0;
//并发许可为 5
static Semaphore s = new Semaphore(1); //如果许可设置为1与ReentrantLock效果一致。
static CountDownLatch c = new CountDownLatch(10); //闭锁
public static void main(String[] args) {
for(int i=0; i<10; i++) {
new Thread(()->{
try {
TimeUnit.MILLISECONDS.sleep(1); //方便模拟出count是线程不安全的状态值
} catch (InterruptedException e) {
e.printStackTrace();
}
count();
c.countDown();
}).start();
}
try {
c.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(count);
}
//count方法最多5个线程同时执行
public static void count() {
try {
s.acquire();
} catch (InterruptedException e) {
}
for(int i=0; i<1000; i++) {
count++;
}
s.release();
}
}
aaa