gpt4 book ai didi

java - 了解信号量...

转载 作者:行者123 更新时间:2023-11-29 03:26:28 28 4
gpt4 key购买 nike

我在这里有一段代码,用于解释信号量的工作原理。无论我多么努力,我都不理解下面的代码以及如何调用信号量的代码。

基本上,代码会尝试模拟许多正在建立的连接......

import java.util.concurrent.Semaphore;

public class Connection {

private static Connection instance = new Connection();

private Semaphore sem = new Semaphore(10, true);

private int connections = 0;

private Connection() {

}

public static Connection getInstance() {
return instance;
}

public void connect() {
try {
sem.acquire();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

try {
doConnect();
} finally {

sem.release();
}
}

public void doConnect() {

synchronized (this) {
connections++;
System.out.println("Current connections: " + connections);
}

try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

synchronized (this) {
connections--;
}

}
}

主类文件..

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;


public class App {

public static void main(String[] args) throws Exception {

ExecutorService executor = Executors.newCachedThreadPool();

for(int i=0; i < 200; i++) {
executor.submit(new Runnable() {
public void run() {
Connection.getInstance().connect();
}
});
}

executor.shutdown();

executor.awaitTermination(1, TimeUnit.DAYS);
}

}

我不理解运行部分

public void run() {
Connection.getInstance().connect();
}

我们如何从上面调用连接方法?在我的判断中,连接输出应该始终是一个,因为正在调用新线程。令人惊讶,但这从未发生过。

最佳答案

我将尝试解释那里发生了什么。以下代码在每个单独的线程中运行,因为您将它提交给线程池:

public void run() {
Connection.getInstance().connect();
}

Connection.getInstance() 在这里返回一个单例(对象 Connection 的单个实例,它在线程之间共享,更多:What is an efficient way to implement a singleton pattern in Java? )。这个单例又包含一个信号量,它也是单一的,并在线程之间共享。因此,在这种情况下,该技术的全部目的是在多个线程之间共享信号量。

connect() 发生了什么:

public void connect() {
try {
// this acquires a single permit for a shared semaphore,
// so no more than 10 threads (the result of new Semaphore(10, true))
// will enter the critical section below simultaneously
sem.acquire();
} catch (InterruptedException e1) {
e1.printStackTrace();
}

try {
// the critical section, at this point there will be 10 threads at max
// this is the purpose of the semaphore
doConnect();
} finally {
// returns the permit acquired, so that a one more thread may
// enter the critical section
sem.release();
}
}

关于java - 了解信号量...,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20761763/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com