只是一个简短而甜蜜的故事。我正在尝试制作一个聊天客户端,因此我有一个线程池来管理服务器上的套接字连接。如果我使用:
while(true) {
thrdPool.execute(new ServChatSocket(servSocket.accept(), InOutMan));
}
这是否会阻止 ServChatSocket 被创建并添加到池中,直到它收到连接,向池中添加一个奇怪的损坏的 ServChatSocket 并产生意外结果,或者抛出某种重复错误,直到收到入站连接?
我是否应该在 while block 中使用 if 语句来检查在传递到 thrdPool 之前是否有对象准备连接?像这样的东西:
while(true) {
if(s = servSocket.accept()) {
thrdPool.execute(new ServChatSocket(s, InOutMan));
}
}
除了防止上述错误(如果有的话)之外,这是否会被认为是更好、更干净的代码?
最佳答案
Will this block ServChatSocket's from being created and added to the pool until it receives a connection
是的。
add a weird broken ServChatSocket to the pool with unexpected results
没有。
or throw some kind of repeated error until it receives an inbound connection?
没有。
Should I use an if statement in the while block to check if there is an object ready to connect before passing to the thrdPool?
没有。 ServerSocket.accept()
永远不会返回 null。
关于java - 这种情况下socket的accept方法会阻塞吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50519017/