Java套接字:你可以从一个线程发送并在另一个线程上接收吗? [英] Java sockets: can you send from one thread and receive on another?

查看:388
本文介绍了Java套接字:你可以从一个线程发送并在另一个线程上接收吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个非常基本的问题,但我很难找到答案。

This is probably an extremely basic question but I'm having difficulty finding an answer.

将一个线程写入Socket的输出流是否可以。线程是从Socket的输入流中读取的?

Is it ok to have one thread writing to a Socket's output stream while another thread is reading from the Socket's input stream?

编辑:这是一个与外部服务器对话的客户端应用程序。我并不是想让两个线程相互通信。抱歉有歧义。

This is a client application that is speaking to an external server. I am not trying to make the two threads talk to each other. Sorry for the ambiguity.

推荐答案

假设你的意思是线程使用相同的套接字与外部actor进行通信而不是每个另外,这很常见,因为你经常不想在等待从套接字读取时阻塞。

Assuming you mean the threads are using the same socket to communicate with an external actor and not with each other, this is pretty common as you often don't want to block while waiting to read from the socket.

线程1:

block on read
on recieve message - do something

线程2:

do things
on something happening - write to socket

如果你的意思是只有两个线程在内部进行通信,你应该研究非套接字替代方案。

If instead you meant just having two threads communicate internally, you should look into non-socket alternatives.

编辑:还要注意潜在的并发问题,所以检查是否有流你使用的是线程安全的。

Also beware of potential concurrency issues, so check whether the streams you are using are thread safe.

这篇关于Java套接字:你可以从一个线程发送并在另一个线程上接收吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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