java.net.Socket threadsafe以什么方式? [英] in what way is java.net.Socket threadsafe?

查看:129
本文介绍了java.net.Socket threadsafe以什么方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Socket,我正在阅读和写入,通过BufferedReaders和BufferedWriters。我不确定哪些操作可以从单独的线程中完成。我猜想同时从两个不同的线程写入套接字是个坏主意。与从两个不同的线程同时读取套接字相同。在另一个线程上写入时在另一个线程上读取怎么办?

I have a Socket that I am both reading and writing to, via BufferedReaders and BufferedWriters. I'm not sure which operations are okay to do from separate threads. I would guess that writing to the socket from two different threads at the same time is a bad idea. Same with reading off the socket from two different threads at the same time. What about reading on one thread while writing on another?

我问,因为我想在读取时长时间阻塞一个线程,因为它等待更多数据,但在这个等待期间,我偶尔也会在套接字上发送数据。我不清楚这是否是线程安全的,或者我是否应该在写之前取消读取(这会很烦人)。

I ask because I want to have one thread blocked for a long time on a read as it waits for more data, but during this wait I also have occasional data to send on the socket. I'm not clear if this is threadsafe, or if I should cancel the read before I write (which would be annoying).

推荐答案

您实际上是从InputStream读取并写入OutputStream。它们相当独立,只要你序列化对它们的访问就可以了。

You actually read from InputStream and write to OutputStream. They are fairly independent and for as long as you serialize access to each of them you are ok.

然而,你必须将你发送的数据与数据相关联。你收到。这与线程安全不同。

You have to correlate, however, the data that you send with data that you receive. That's different from thread safety.

这篇关于java.net.Socket threadsafe以什么方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆