如何安全地将可变对象从一个线程发布到另一个线程 [英] How to safely publish mutable object from one thread to another

查看:125
本文介绍了如何安全地将可变对象从一个线程发布到另一个线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有一个可变类Foo(或ArrayList为例),没有同步。
这样一个对象的构造需要时间,所以我想在一个单独的线程中执行它。

For example I have a mutable class Foo(or ArrayList for example) with no synchronization. Construction of such an object needs time so I'd like to perform it in a separate thread.

如果我存储在某处的计算结果和以后的访问它从另一个线程不会是线程安全的,因为同步或volatile需要,对吗? (我实际上不太确定这里)

If I store somewhere the result of computation and later access it from another thread that wold not be thread safe, because synchronization or volatile required, right? (I am actually not quite sure here)

所以我正在寻找一种方法将一个对象从一个线程传递到另一个没有同步的Foo。

So I'm looking for a way to pass such an object from one thread to another without synchronizing of Foo.

推荐答案

您的要求符合生产者消费模式。 Java的并发包a提供线程安全的集合(像 BlockingQueue 等)。生产者将创建对象并将其放在 BlockingQueue 上。消费者然后拾起对象。以下是示例实施

Your requirement matches the Producer Consumer Pattern. Java's concurrent package a offers thread-safe collections (Like BlockingQueue etc ). Producer will create the object and put it on BlockingQueue. The Consumer then picks up the object. Here is example implementation.

这篇关于如何安全地将可变对象从一个线程发布到另一个线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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