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