面试题:Semaphore

更新时间:2023-07-23 03:20:32 阅读: 评论:0

⾯试题:Semaphore
1、Semaphore 是什么
Semaphore 通常我们叫它信号量, 可以⽤来控制同时访问特定资源的线程数量,通过协调各个线程,以保证合理的使⽤资源。
可以把它简单的理解成我们停车场⼊⼝⽴着的那个显⽰屏,每有⼀辆车进⼊停车场显⽰屏就会显⽰剩余车位减1,每有⼀辆车从停车场出去,显⽰屏上显⽰的剩余车辆就会加1,当显⽰屏上的剩余车位为0时,停车场⼊⼝的栏杆就不会再打开,车辆就⽆法进⼊停车场了,直到有⼀辆车从停车场出去为⽌。
2、使⽤场景
主要⽤于那些资源有明确访问数量限制的场景,常⽤于限流 。
⽐如:数据库连接池,同时进⾏连接的线程有数量限制,连接不能超过⼀定的数量,当连接达到了限制数量后,后⾯的线程只能排队等前⾯的线程释放了数据库连接才能获得数据库连接。
public class TestPoolSemaphore {
public static void main(String[] args) {
Pool pool = new Pool(2);
for (int i = 0; i < 5; i++) {
new Thread(() -> {
Connection conn = pool.borrow();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
pool.free(conn);
}).start();
}
}
}
@Slf4j(topic = "c.Pool")
class Pool {
// 1. 连接池⼤⼩
private final int poolSize;
// 2. 连接对象数组
private Connection[] connections;
// 3. 连接状态数组 0 表⽰空闲, 1 表⽰繁忙
private AtomicIntegerArray states;
private Semaphore maphore;
// 4. 构造⽅法初始化
public Pool(int poolSize) {
this.poolSize = poolSize;
// 让许可数与资源数⼀致
this.maphore = new Semaphore(poolSize);
this.states = new AtomicIntegerArray(new int[poolSize]);
for (int i = 0; i < poolSize; i++) {缩句大全
connections[i] = new MockConnection("连接" + (i+1));
}
}
// 5. 借连接
public Connection borrow() {// t1, t2, t3
// 获取许可
try {
maphore.acquire(); // 没有许可的线程,在此等待
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < poolSize; i++) {
// 获取空闲连接
(i) == 0) {
if (pareAndSet(i, 0, 1)) {
log.debug("borrow {}", connections[i]);
return connections[i];
}
}
}
// 不会执⾏到这⾥
return null;
}
// 6. 归还连接
public void free(Connection conn) {
for (int i = 0; i < poolSize; i++) {
if (connections[i] == conn) {
states.t(i, 0);
log.debug("free {}", conn);
break;
壁纸图片}
}
}
}
class MockConnection implements Connection {
private String name;
public MockConnection(String name) {
this.name = name;
}
@Override
public String toString() {
return "MockConnection{" +
"name='" + name + '\'' +
'}';
}
@Override
public Statement createStatement() throws SQLException {
return null;
}
@Override
public PreparedStatement prepareStatement(String sql) throws SQLException {        return null;
}
猪九妹@Override
public CallableStatement prepareCall(String sql) throws SQLException {满开头的成语
return null;
}
@Override
public String nativeSQL(String sql) throws SQLException {
return null;
}
@Override
public void tAutoCommit(boolean autoCommit) throws SQLException {
}
@Override
public boolean getAutoCommit() throws SQLException {
return fal;
}
@Override
public void commit() throws SQLException {
}
@Override
保险销public void rollback() throws SQLException {
}
@Override
public void clo() throws SQLException {
}
@Override
public boolean isClod() throws SQLException {
return fal;
}
@Override
public DatabaMetaData getMetaData() throws SQLException {
return null;
}
@Override
public void tReadOnly(boolean readOnly) throws SQLException {
}
@Override
public boolean isReadOnly() throws SQLException {
return fal;
}
@Override
public void tCatalog(String catalog) throws SQLException {
}
@Override
public String getCatalog() throws SQLException {
return null;
}
@Override
public void tTransactionIsolation(int level) throws SQLException {
}
@Override
public int getTransactionIsolation() throws SQLException {
return 0;
}
@Override
public SQLWarning getWarnings() throws SQLException {
return null;
}
@Override
public void clearWarnings() throws SQLException {
}
@Override
public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
return null;
}
@Override
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {        return null;
}
@Override
田忌赛马图片
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws
SQLException {
return null;
}
@Override
public Map<String, Class<?>> getTypeMap() throws SQLException {
return null;
}
@Override
public void tTypeMap(Map<String, Class<?>> map) throws SQLException {
}
@Override
public void tHoldability(int holdability) throws SQLException {
}
@Override
public int getHoldability() throws SQLException {
return 0;
}
@Override
public Savepoint tSavepoint() throws SQLException {
return null;
}
@Override
public Savepoint tSavepoint(String name) throws SQLException {
return null;
}
@Override
public void rollback(Savepoint savepoint) throws SQLException {
}
@Override
public void releaSavepoint(Savepoint savepoint) throws SQLException {
}
@Override
public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
return null;
}
@Override
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLExceptio n {
return null;
}
@Override
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
return null;
}
@Override
public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
return null;
}
@Override
public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
return null;
}儿童诗
@Override
public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {
return null;
}
@Override
public Clob createClob() throws SQLException {
return null;
}
@Override
public Blob createBlob() throws SQLException {
return null;
}
@Override
public NClob createNClob() throws SQLException {
return null;
}
@Override
public SQLXML createSQLXML() throws SQLException {
return null;
}
@Override
public boolean isValid(int timeout) throws SQLException {
return fal;
}
@Override
public void tClientInfo(String name, String value) throws SQLClientInfoException {
}
@Override
public void tClientInfo(Properties properties) throws SQLClientInfoException {
}
@Override
public String getClientInfo(String name) throws SQLException {
return null;
}
@Override
public Properties getClientInfo() throws SQLException {
return null;
}
@Override
public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
return null;
}
@Override
public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
return null;
}
@Override
public void tSchema(String schema) throws SQLException {
}
@Override
public String getSchema() throws SQLException {
return null;
}
@Override
public void abort(Executor executor) throws SQLException {
}
@Override
public void tNetworkTimeout(Executor executor, int milliconds) throws SQLException {
}
@Override
public int getNetworkTimeout() throws SQLException {
return 0;
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
return null;
男鸡女兔婚配是否合适
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return fal;
}
}
⽐如:停车场场景,车位数量有限,同时只能容纳多少台车,车位满了之后只有等⾥⾯的车离开停车场外⾯的车才可以进⼊。/**
* @author WGR
* @create 2020/12/27 -- 22:19
*/
public class Test1 {
public static void main(String[] args) {
// 1. 创建 maphore 对象
Semaphore maphore = new Semaphore(3);
// 2. 10个线程同时运⾏
for (int i = 0; i < 10; i++) {
final int x = i;
new Thread(() -> {
// 3. 获取许可
try {

本文发布于:2023-07-23 03:20:32,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/fan/82/1111999.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:连接   数量   线程   停车场   限制   数据库
相关文章
留言与评论(共有 0 条评论)
   
验证码:
推荐文章
排行榜
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图