说一说你对Semaphore的理解(谈谈你对sem的理解)
【死记硬背】
【概念】Semaphore即信号量,是一种计数器,用来保护一个或者多个共享资源的访问,它是并发编程的一种基础工具,用来控制同时访问的线程个数。
【原理】Semaphore实现临界区必须遵循三个步骤,首先,必须通过acquire()方法获得信号量;其次,使用共享资源执行必要的操作;最后,必须通过release()方法释放信号量。
Semaphore通过acquire()方法获取一个许可,如果没有就等待,而release()方法则释放一个许可。acquire()和release()是Semaphore的两个重要方法。
Semaphore的有参构造器Semaphore(int permits, boolean fair)提供了第二个传入参数,可以设置信号量是否为公平模式,如果传入的是false,那边就是非公平模式,如果传入的是true,则信号量是公平模式,默认是非公平模式。
【答案解析】
Semaphore的使用样例如下:
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();
//只能几个线程同时访问
final Semaphore semph = new Semaphore(3);
//模拟几个客户端访问
for(int index=1;index<10;index++) {
final int NO=index;
Runnable ru = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
//获取许可
semph.acquire();
System.out.println("accessing:"+NO);
Thread.sleep((long)(Math.random()*1000));
//访问完后,释放
System.out.println("release:"+NO);
semph.release();
}catch (Exception e) {
// TODO: handle exception
}
}
};
exec.execute(ru);
}
//退出线程池
exec.shutdown();
}
}
【温馨提示】
点赞+收藏文章,关注我并私信回复【面试题解析】,即可100%免费领取楼主的所有面试题资料!