发送对象和线程同步
我读到,当将一个对象发送到函数/另一个对象时,发送的不是实际的对象,而是他的副本。因此,在多线程处理时,我有一个大小为 1 的 ArrayBlockingQueue 和两个类——生产者和消费者(它们是线程的扩展),它们相应地读取和写入数据,这样:
ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>();
Producer add = new Producer(queue);
Consumer show = new Consumer(queue);
我不会发送给构造函数“队列”变量本身,而是它的副本。那么,这两个对象都有不同的队列,所以这两个对象之间不会有任何误解,对吗?如果是的话,为什么我们需要线程同步?如果没有,为什么?
I read that when sending an object to the function/another object, not the actual object is sent, but his copy. So, when multithreading, I have a ArrayBlockingQueue with size of one, and two classes -- Producer and Consumer (which are extensions of Thread), which read and write the data, accordingly, this way:
ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>();
Producer add = new Producer(queue);
Consumer show = new Consumer(queue);
I'm not sending to the constructors the "queue" variable itself, but the copy of it. So, both of objects have different queues, so there's not going to be any misunderstanding between these two objects, right? If yes, why do we need thread synchronization? If no, why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是不正确的。 Java 按值传递,但它按值传递引用。因此,队列引用的副本被传递给生产者和消费者。但是,不会复制引用的对象。
This is incorrect. Java passes by value, but it passes references by value. So a copy of the queue's reference is passed to the producer and consumer. However, the object referenced is not copied.
不,
add
和show
都将引用同一个对象,即ArrayBlockingQueue
(称为queue
)。如果你想一想,只传播副本并没有多大好处。施工结束后,实际信息将如何传递?
由于
add
和show
可能位于不同的线程中,因此您需要一个同步机制。No,
add
andshow
both would have a reference to the same object, theArrayBlockingQueue
known asqueue
.If you think about it, it wouldn't do very much good to have only copies passed around. How would actual information ever get passed around after construction time?
Since presumably
add
andshow
are in different Threads, you need a synchronization mechanism.在您的示例中,您将相同对象传递给添加和显示对象。您没有传递副本。因此,add 的任何操作可能都会对show产生影响,因此在这种情况下需要线程同步
In your example, you are passing the same object to both the add and show objects. You are not passing a copy. Therefore any operations by add may have an impact on show so thread synchronisation is required in this case