努力理解这个概念:线程主要通过共享对字段的访问来通信,对象引用字段指的是

Struggling to understand the concept: Threads communicate primarily by sharing access to fields and the objects reference fields refer to

我是 Java 的新手,对其中的一些概念感到困惑。我在 Java Oracle 教程中看到了这个声明:"Threads communicate primarily by sharing access to fields and the objects reference fields refer to." 有人可以向我解释一下 "the objects reference fields refer to" 是什么意思吗? "object reference" 是什么?提前致谢!!

一个非常基本的答案是,当一个线程可以访问一个对象时,其他线程不应该能够同时访问同一个对象,并且它们也不应该能够访问对象引用。

关于对象引用,引用自上面链接的What is Object Reference Variable?

A reference is what is used to describe the pointer to the memory location where the Object resides.

线程应该使用对象和它们之间的对象引用共享时间,确保避免对象与永远不会释放对象供另一个线程使用的线程发生死锁。

这里是the quote

Threads communicate primarily by sharing access to fields and the objects reference fields refer to. This form of communication is extremely efficient, but makes two kinds of errors possible: thread interference and memory consistency errors. The tool needed to prevent these errors is synchronization.

引用是指向内存中对象的指针。共享引用意味着属于一个线程正在执行的对象的引用被复制到另一个线程正在访问的对象中。

假设我们有一个队列,其中一些线程将东西放入队列中,而其他线程则从队列中取出东西。当一个线程将一个对象放入队列时,它从引用该对象的线程(称为生产者)开始,然后在将其放入队列后,队列将引用它。然后其他一些正在使用队列中的项目的线程出现并从队列中获取对象,现在消费者线程正在引用它。所以对象引用在线程之间传递。

本教程讨论的是为了将引用可靠地从一个线程传递到另一个线程而需要采取的措施。对跨线程可见的对象进行更改太昂贵了,无法一直这样做,当您想将更改发布到另一个线程时,您必须做一些特定的事情,例如锁定或使用 volatile 关键字。