java - Java IO 是阻塞 IO 吗?

标签 java sockets networking io websocket

我知道对于一个线程(一个套接字),我不能同时执行 read() 或 write(),或者可以吗?

但是如果我创建 2 个线程并且每个线程分别处理 read() 和 write() 会怎么样?我不知道在低级别 View 中,read()和write()是否会获得套接字锁,因此一次只允许执行一项操作?会吗?

我使用Window作为平台,但也想知道Unix机器上有什么不同吗?

我问这个问题是因为我很困惑,既然两个线程能够让我们同时进行 read() 和 write() 操作,为什么我们需要非阻塞 IO?

最佳答案

I know for ONE thread (one socket), I cannot perform read() or write() at the same time, or can I?

当然不是。一个线程一次只能调用一个方法。这个问题没有意义。

But what if I create 2 thread and each of them handle read() and write() separately? I don't know in low level view, will the read() and write() obtain the socket lock, so only one operation is allowed to execute at one time? Will it?

他们不需要锁。 TCP 是全双工的。您可以在同一个套接字上读取和写入。同时。

I am using Window as the platform, but also like to know is there different in Unix machine?

没有。

I ask this question because I am confused that, why we need non-blocking IO since 2 threads are able to let us read() and write() simultaneously?

下定决心吧。首先你问是否可能,现在你(正确地)说可以。

NIO 允许您在同一线程中处理多个套接字。这样做的目的是保护线程,例如在必须处理数十万个连接的服务器中。

关于java - Java IO 是阻塞 IO 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12361877/

相关文章:

java - JMenu 在调整窗口大小之前不会出现

java - BufferedImage 始终从 ByteArrayInputStream 传入 null

游戏中的网络问题

swift - TCP 套接字流和 SSL 与 Swift

linux - 多次绑定(bind)到同一个端口

azure - Azure VM 的多个公共(public) IP

Java 正则表达式不适用于文件验证

java - 到底什么是链接(符号或其他)

java - 无法模拟 EntityManager jMockit

node.js - 将我的 SSL key 和证书文件传递给 Socket.IO 是否安全?