线程唯一数据

发布于 2024-11-14 09:01:12 字数 148 浏览 1 评论 0原文

我需要维护一个哈希图,它应该对所有正在执行的线程公开。 例如,由一个特定线程更新的哈希图也应该可供其他线程使用,反之亦然。请建议我用Java实现。

主程序包含哈希图。从这个主线程我将触发许多线程。每个线程应该访问主程序中可用的相同哈希图。

提前致谢。

I need to maintain a hashmap which should be public to all the threads executing.
For example the hashmap updated by one particular thread should be available to the other threads also and vice versa. Please suggest me with the implementation in Java.

The main program contains the hashmap. From this main thread i will be trigerring many threads. Each thread should access the same hashmap available in the main program.

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

尸血腥色 2024-11-21 09:01:12

在这里查找所有线程安全的数据结构......
http://download.oracle.com /javase/6/docs/api/java/util/concurrent/package-summary.html

我猜你需要一个并发哈希映射。如果您可以将映射更改为列表,则可以使用 CopyOnWriteArrayList,它允许以高效的头部安全方式对列表进行读写。

look here for all thread safe data structures...
http://download.oracle.com/javase/6/docs/api/java/util/concurrent/package-summary.html

i guess you need a concurrent hash map. If you can change your map to a list, you can use CopyOnWriteArrayList which allows a highly efficient thead safe way to read write to a list.

平定天下 2024-11-21 09:01:12

Java 中的问题不在于在多个线程之间共享变量:只需将对对象的引用传递给线程即可轻松完成。请记住,您需要确保安全地访问它...并发修改可能会很麻烦。我建议您查看java并发教程,这是一个非常好的起点: http://download.oracle.com/javase/tutorial/essential/concurrency/index.html

The problem in Java is not sharing a variabile between multiple threads: you can do it easily just passing the reference to the object to the thread. Please keep in mind that you need to be sure to access it safely... Concurrent modification can be a trouble. I suggest you to check java concurrency tutorial, it is a very good starting point: http://download.oracle.com/javase/tutorial/essential/concurrency/index.html

一身骄傲 2024-11-21 09:01:12

不要将其设为静态 - 这样会导致并发问题,并使您的代码难以测试。相反,使用并发哈希映射:

http ://download.oracle.com/javase/1,5.0/docs/api/java/util/concurrent/ConcurrentHashMap.html

并将对其的引用传递给每个需要它的线程。

Dont make it static - that way lies concurrency problems, and makes your code less testable. Instead, use a concurrent hash map:

http://download.oracle.com/javase/1,5.0/docs/api/java/util/concurrent/ConcurrentHashMap.html

And pass a reference to it to each thread that needs it.

独夜无伴 2024-11-21 09:01:12

哈希映射可以设为静态,并且可以使用 ClassName 在线程中访问。我想这是一种解决方案,但并发可能是一个问题。期待关于这个问题的任何好的解决方案。

The hashmap can be made static and can be accessed in the threads using the ClassName. I guess it is one solution but concurrency might be a problem. Expecting anyother good solution regarding this issue.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文