Java套接字是否支持全双工? [英] Do Java sockets support full duplex?
问题描述
是否可以让一个线程写入Java Socket
的 OutputStream
,而另一个线程则从socket的 InputStream
,没有线程必须在套接字上同步?
Is it possible to have one thread write to the OutputStream
of a Java Socket
, while another reads from the socket's InputStream
, without the threads having to synchronize on the socket?
推荐答案
确定。你所描述的确切情况应该不是问题(同时读写)。
Sure. The exact situation you're describing shouldn't be a problem (reading and writing simultaneously).
一般来说,如果没有什么可读的话,读取线程会阻塞,并且可能如果指定了超时,则读取操作超时。
Generally, the reading thread will block if there's nothing to read, and might timeout on the read operation if you've got a timeout specified.
由于输入流和输出流是Socket中的单独对象,因此您可能只关注它你自己是,如果有2个线程同时尝试读取或写入(两个线程,相同的输入/输出流)会发生什么? InputStream / OutputStream类的读/写方法不同步。但是,如果您使用的是InputStream / OutputStream的子类,则可能会同步您正在调用的读/写方法。您可以查看javadoc以查找您正在调用的任何类/方法,并快速找到它。
Since the input stream and the output stream are separate objects within the Socket, the only thing you might concern yourself with is, what happens if you had 2 threads trying to read or write (two threads, same input/output stream) at the same time? The read/write methods of the InputStream/OutputStream classes are not synchronized. It is possible, however, that if you're using a sub-class of InputStream/OutputStream, that the reading/writing methods you're calling are synchronized. You can check the javadoc for whatever class/methods you're calling, and find that out pretty quick.
这篇关于Java套接字是否支持全双工?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!