简体   繁体   English

发送对象和线程同步

[英]Sending an object and threads synchronization

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的类,以及两个类-Producer和Consumer(它们是Thread的扩展),它们分别以这种方式读取和写入数据:

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. 我不是将“ queue”变量本身发送给构造函数,而是发送给它的副本。 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? 如果没有,为什么?

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. Java按值传递,但按值传递引用。 So a copy of the queue's reference is passed to the producer and consumer. 因此,队列引用的副本将传递给生产者和消费者。 However, the object referenced is not copied. 但是,引用的对象不会被复制。

No, add and show both would have a reference to the same object, the ArrayBlockingQueue known as queue . 不, addshow两个对象都将引用同一对象ArrayBlockingQueuequeue

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. 由于推测addshow位于不同的线程中,因此您需要一种同步机制。

In your example, you are passing the same object to both the add and show objects. 在您的示例中,您将同一对象传递给add和show对象。 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 因此,通过add进行的任何操作都可能会影响演出,因此在这种情况下需要线程同步

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM