仍然处于用Java学习oop概念的阶段。在oracle教程这里中提供的并发示例中(请容忍我并快速查看它,很容易),producerconsumerexample类触发producer和consumer的两个线程,这两个线程都应该通过Drop对象drop交换数据。在这个对象中,他们应该等待/得到对方的通知。
public class ProducerConsumerExample {
public static void main(String[] args) {
Drop drop = new Drop();
(new Thread(new Producer(drop))).start();
(new Thread(new Consumer(drop))).start();
}
}我不明白的是,drop对象是由producerconsumerexample类传递给每个线程的,这给我们提供了两个新的本地Drop对象,也称为drop,每个线程中有一个。据我所知,这是因为传入Java是根据值而不是引用。因此,每个线程现在都有自己版本的Drop对象,那么为什么它们仍然应该通过相同的原始Drop对象共享数据,因为每个线程都有自己的版本?!
谁来帮帮忙,我会很感激的。
发布于 2017-06-25 18:16:25
如果您谈到这个示例,并且删除变量-它的对象,那么在java中,所有对象都通过引用传递,而不是通过值传递。生产者和消费者的工作对象相同。对于按值传递的原语
public class ProducerConsumerExample {
public static void main(String[] args) {
Drop drop = new Drop();
(new Thread(new Producer(drop))).start();
(new Thread(new Consumer(drop))).start();
}
}发布于 2017-06-25 18:19:29
有点不一样。正如您所说的,Java是通过值传递的,而不是通过引用传递的,但是当我们传递对象的值时,我们传递的是对它的引用。
起初,这可能是一种误解,因为他们决定将对象的位置称为“引用”。
因此,Procuder和Consumer保存相同的引用,因此它们处理的对象是相同的。
例如:
class Foo {
Bar x;
public Foo(Bar v) { this.x = v; }
public String getString() { return x.y; }
}
class Bar {
String y;
public Bar() {}
}
class Test {
public static void main(String[] args) {
Bar x1 = new Bar();
x1.y = "Test1";
Foo x2 = new Foo(x1);
/* the method getString() returns "Test1" */
System.out.println(x2.getString());
/* If I change x1.y, x2.getString() returns a different element */
x1.y = "Test 2";
System.out.println(x2.getString());
}
}https://stackoverflow.com/questions/44749176
复制相似问题