实例如何与其实例化器通信? [英] How can an instance communicate with its instantiator?
问题描述
给出一个非常简单的例子:
Given a really oversimplified example:
Class A {
B b = new B();
}
Class B {
//unicorns and what-not
//Something happens and I want to let A know
//Yet I don't want to return and exit
}
B可以通过任何方式进行交流吗?有一个没有插座的?
通过交流,我的意思是B将值发送给A而没有A在B上调用方法。
Is there any way that B can communicate with A without Sockets? By communicate, I mean B sending values to A without A invoking a method on B.
编辑:谢谢您的支持回应。以下是我的后续问题:
EDIT: Thank you for your responses. This following is my follow up question:
如果我有以下内容,并且2个B实例同时调用了signal()方法,这将导致每个B两次调用动作。我该怎么办?
If I had the following, and method signal() is called simultaneously by 2 instances of B, this will cause a conflict of every B calling action twice. What can I do to solve it?
//Modified from Jon Skeet
public class A {
private B b[];
public A() {
//for loop
b[i] = new B(this);
}
public void signal() {
//for loop
b[i].action();
}
}
public class B {
A creator;
public B(A creator) {
this.creator = creator;
}
public void action() {
//stuff
}
public void main(String[] args) {
while(true)
if(something==true) {
creator.signal();
}
}
}
推荐答案
让他们两个都访问同一个 Queue
。一个放置元素,另一个放置元素。如果它们在不同的线程中,则 BlockingQueue
实现应该可以解决问题。
Give them both access to the same Queue
. One puts elements onto it, the other pulls elements from it. If they're in separate threads, one of the BlockingQueue
implementations should do the trick.
这篇关于实例如何与其实例化器通信?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!