java并发:线程同步机制之Semaphore
一、初识Semaphore
![]()


小结:
A、可以将信号量可视化为一个计数器,它可以递增或递减。
B、从概念上讲,信号量维护了一个许可集合,Semaphore对可用的许可进行计数。
C、当计数器的值为0时,它能够使线程等待。
二、示例
The three steps you must follow when you use a semaphore to implement a critical section and protect the access to a shared resource:
- First, you acquire the semaphore, with the acquire() method.
- Then, you do the necessary operations with the shared resource.
- Finally, release the semaphore with the release() method.
场景:
假设一个服务器资源有限,任意某一时刻只允许3个人同时访问,这时一共来了10个人
package com.test;
import java.util.concurrent.Semaphore;
public class SemaphoreDemo{
public static void main(String args[]) throws Exception{
final Semaphore semaphore = new Semaphore(3);//一次只允许3个人进行访问
for(int i=0;i<10;i++) {
final int no = i;
Runnable thread = new Runnable() {
public void run (){
try {
System.out.println("用户"+no+"连接上了:");
Thread.sleep(300L);
semaphore.acquire();//获取执行的许可
System.out.println("用户"+no+"开始访问后台程序...");
Thread.sleep(1000L);//模仿用户访问服务过程
semaphore.release();//释放,允许下一个线程访问后台
System.out.println("用户"+no+"访问结束。");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
new Thread(thread).start();
}
System.out.println("Main thread end!");
}
}


