发送对象和线程同步

发布于 2024-11-03 08:14:31 字数 410 浏览 0 评论 0原文

我读到,当将一个对象发送到函数/另一个对象时,发送的不是实际的对象,而是他的副本。因此,在多线程处理时,我有一个大小为 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 技术交流群。

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

发布评论

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

评论(3

慢慢从新开始 2024-11-10 08:14:31

我读到,当将一个对象发送到函数/另一个对象时,发送的不是实际的对象,而是他的副本。

这是不正确的。 Java 按值传递,但它按值传递引用。因此,队列引用的副本被传递给生产者和消费者。但是,不会复制引用的对象。

I read that when sending an object to the function/another object, not the actual object is sent, but his copy.

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.

梦在深巷 2024-11-10 08:14:31

不,addshow 都将引用同一个对象,即 ArrayBlockingQueue(称为queue)。

如果你想一想,只传播副本并没有多大好处。施工结束后,实际信息将如何传递?

由于 addshow 可能位于不同的线程中,因此您需要一个同步机制。

No, add and show both would have a reference to the same object, the ArrayBlockingQueue known as queue.

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 and show are in different Threads, you need a synchronization mechanism.

旧伤慢歌 2024-11-10 08:14:31

在您的示例中,您将相同对象传递给添加和显示对象。您没有传递副本。因此,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

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