java在线程之间共享数据 [英] java share data between thread

查看:179
本文介绍了java在线程之间共享数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从socket服务器读取数据的java进程。因此,我有一个 BufferedReader 和一个 PrintWriter 对应该套接字的对象。

i have a java process that reads data from a socket server. Thus i have a BufferedReader and a PrintWriter object corresponding to that socket.

现在在同一个java进程中,我有一个接受客户端连接的多线程java服务器。我想实现一个功能,其中我接受的所有这些客户端都可以从我上面提到的 BufferedReader 对象中读取数据。(这样它们可以复用数据)

Now in the same java process i have a multithreaded java server that accepts client connections. I want to achieve a functionality where all these clients that i accept can read data from the BufferedReader object that i mentioned above.(so that they can multiplex the data)

如何让这些单独的客户端线程从BuffereReader单个对象读取数据?很抱歉这是混乱。

推荐答案

我强烈建议他们直接访问 BufferedReader 。假设你知道数据的格式,并且每个客户端都试图读取相同的格式(如果不是这种情况,我看不出它是如何工作的)我建议创建一个线程来读取 BufferedReader 并将工作项放在 Queue 中。在Java中使用生产者/消费者队列的示例有 lot ,这也可能使测试客户端代码变得更容易。

I would strongly suggest that they don't access the BufferedReader directly. Assuming you know the format of the data, and that each client is trying to read the same format (if that's not the case, I can't see how it could work at all) I would suggest creating one thread to read from the BufferedReader and put work items in a Queue. There are lots of example of using producer/consumer queues in Java, and this is also likely to make it easier to test the client code.

只有一个线程访问 BufferedReader 意味着您不必担心定义所有其他线程必须包含的原子操作 - 您的阅读线程有效地定义了决定将工作项添加到队列中的操作。

Having only one thread accessing the BufferedReader means you don't need to worry about defining an atomic operation that all other threads will have to content for - your reading thread effectively defines that operation by deciding to add a work item to the queue.

编辑:如果所有客户端都应该看到所有数据,那就会强化我的建议让一个读者更进一步 - 除了没有一个 Queue 的数据被删除的项目,你有一个集合,客户可以读取所有来自的现有数据。你需要使用一个适当的线程安全的集合,但有很多用Java。

If all the clients should see all of the data, that reinforces my suggestion of having a single reader even further - except instead of having a Queue of data which items are removed from, you'd have a collection which clients can read all the existing data from. You'll need to use an appropriately thread-safe collection, but there are plenty of those in Java.

编辑:刚看完你的评论说每个客户应该只需看看读者阅读的最后一项,即可轻松实现。让一个线程读取数据,但只保留一个变量,并引用最后读取的项目。您可能要么同步对它的访问权限,要么使用 AtomicReference ,但这两种方法都很简单。

Having just read your comment which says that each client should just see the last item read from the reader, that makes it even easier. Have one thread reading the data, but just keep a single variable with a reference to "the last item read". You probably either want to synchronize access to it or use an AtomicReference, but both of those are easy.

这篇关于java在线程之间共享数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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