Semaphore:计数信号量
作用:信号量通常用于限制线程数,而不是访问某些(物理或逻辑)资源,可以用作互斥锁,每个acquire()方法都会阻
塞线程,每个release()方法都会释放线程,限制线程的并发数量
在某种情况下使用Semaphore代替Synchronized
以下为测试代码:
public class TestSemaphore {
private Semaphore semaphore = new Semaphore(1);
public void test(){
try{
semaphore.acquire();
System.out.println(Thread.currentThread().getName()+"-sbegin");
Thread.currentThread().sleep(2000);
System.out.println(Thread.currentThread().getName()+"-end");
semaphore.release();
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
public class TestThread extends Thread{
private TestSemaphore testSemaphore;
public TestThread(TestSemaphore testSemaphore){
this.testSemaphore = testSemaphore;
}
@Override
public void run() {
testSemaphore.test();
}
}
public class MyTest {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(5);
TestSemaphore testSemaphore = new TestSemaphore();
for(int i=0;i<5;i++){
TestThread thread = new TestThread(testSemaphore);
executorService.submit(thread);
}
executorService.shutdown();
}
}
打印结果:
pool-1-thread-1-sbegin
pool-1-thread-1-end
pool-1-thread-3-sbegin
pool-1-thread-3-end
pool-1-thread-2-sbegin
pool-1-thread-2-end
pool-1-thread-5-sbegin
pool-1-thread-5-end
pool-1-thread-4-sbegin
pool-1-thread-4-end