Mig*_*eno 3 java multithreading httpserver executors
我正在构建一个需要同时处理多个请求的 HTTPServer。
我构建的主要功能如下:
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
server.createContext("/", new MyRequestDispatcher());
server.setExecutor(Executors.newCachedThreadPool());
server.start();
}
Run Code Online (Sandbox Code Playgroud)
现在我正在考虑它如何Executors.newCachedThreadPool()在创建的线程数量方面发挥作用。正如我所读到的,要创建的线程数量不受限制,如果我同时收到一千个请求,它会创建一千个线程吗?
我正在考虑限制同时创建的线程数量,以便在运行它的机器中正确处理。我想到了这样的事情:
Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors())
Run Code Online (Sandbox Code Playgroud)
目标是根据系统中的可用处理器仅创建给定数量的线程。
这行得通吗?
提前致谢!!
是的,它会起作用,而且这是您最常看到的推荐。
根据您的具体用例,您可能仍然想使用不同的号码。