问题
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
}
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:
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();
}
}
}
回答1:
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.
回答2:
You'd have to pass this into the constructor for B:
public class A {
private B b;
public A() {
b = new B(this);
}
}
public class B {
A creator;
public B(A creator) {
this.creator = creator;
}
}
Admittedly it's generally not a great idea to let this "escape` in the constructor, but every so often it's cleaner than the alternatives.
回答3:
// unicorns and what-not
If A passes B an instance of itself in the constructor, you ain't need no stinkin unicorns:
class B {
A instantiator;
public B(A inst) { instantiator = inst; }
}
class A {
B b = new B(this);
}
EDIT (to answer the follow-up question)
If you would like to make sure that multiple invocations of signal do not modify the the state of A concurrently, you should protect its critical sections by using synchronized keyword. If the entire method represents a single critical section, you can add synchronized to method's declaration, like this:
public synchronized void signal() {
//for loop
b[i].action();
}
回答4:
Class A {
B b = new B(this);
public void MyCallback(Object o) {
//Whatever
}
}
Class B {
//unicorns and what-not
private A a;
// .... assign a in constructor ...
// wherever
a.MyCallback(MyUnicorn);
}
来源:https://stackoverflow.com/questions/11214152/how-can-an-instance-communicate-with-its-instantiator