Java:什么对象更合适?
我正在编写一个类似于聊天服务器-客户端对的应用程序。
我计划有一个中心对象,它将保存从客户端收到的新消息,直到它们被主线程处理。
我的应用程序是多线程的。每个客户端都将位于自己的线程上,因此多个线程将向该中心对象添加消息。
主线程将检查该对象的消息,删除“最旧的”对象并进行适当的处理。最好我希望按照添加消息的顺序(先进先出)来处理消息。
什么类型的对象最适合保存新消息?我研究了 Vectors 和 ArrayLists,但我对同步方面感到困惑。我以前从未使用过同步或线程。
谢谢
I am writing an application similar to a chat server-client pair.
I am planning on having a central Object which will hold new messages received from clients until they are dealt with by the main thread.
My application is multi-threaded. Each client will be on its own thread, so multiple threads will be adding messages to this central Object.
The main thread will check this Object for messages, remove the "oldest" and deal with it appropriately. Preferably I would like the messages to be handled in the same order they were added (FIFO).
What type of Object is most appropriate to hold the new messages? I looked into Vectors and ArrayLists, but I am confused about the synchronization aspect. I never worked with synchronization or threads before.
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
ConcurrentLinkedQueue 听起来很可能。
更多信息请参见:如何使用 ConcurrentLinkedQueue?
这里的 Javadoc:http://download-llnw.oracle.com/javase/ 1.5.0/docs/api/java/util/concurrent/ConcurrentLinkedQueue.html
ConcurrentLinkedQueue
sounds likely.More info here: How to use ConcurrentLinkedQueue?
Javadoc here: http://download-llnw.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/ConcurrentLinkedQueue.html
如果这不仅仅是一个小玩具项目,您应该查看 JMS 解决了您尚未意识到的所有小问题。
JMS 的一个很好的实现是 Apache ActiveMQ(与 IBM 的 MQSeries 无关)。
If this is to become more than a little toy project, you should look into JMS which solves all of the little problems that you're not aware of, yet.
A good implementation of JMS is Apache ActiveMQ (not related to IBM's MQSeries).
您还可以考虑使用 jgroups 来完成此项目。
JGroups 是一个开源可靠的群组通信工具包。其可靠且易于使用。这是教程中的基本聊天示例。
You may also consider jgroups for this project.
JGroups is an open source reliable group communication toolkit. Its reliable and simple to use. Here is a basic chat example in the tutorial of same.
虽然不是一个直接的答案(@Alison 提供了一个足够好的答案,只要您不需要持久化消息),每当您需要数据结构类或实用程序类来帮助处理多个问题时,请始终查看 java.util.concurrent 包- 线程编码: http: //download-llnw.oracle.com/javase/6/docs/api/java/util/concurrent/package-summary.html
While not a direct answer (As @Alison provided a decent enough of one provided you don't need to persist messages) always have a look at the java.util.concurrent package whenever you need data structure classes or utility classes to help with multi-threaded coded: http://download-llnw.oracle.com/javase/6/docs/api/java/util/concurrent/package-summary.html