简体   繁体   中英

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<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?

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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