0

给出一个非常简单的例子:

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 在没有套接字的情况下与 A 通信?通过通信,我的意思是 B 向 A 发送值,而 A 不调用 B 上的方法。

编辑:感谢您的回复。以下是我的后续问题:

如果我有以下情况,并且方法 signal() 被 B 的 2 个实例同时调用,这将导致每个 B 调用操作两次发生冲突。我能做些什么来解决它?

//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();
            }

   }
}
4

4 回答 4

4

您必须传递this给 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;
    }
}

诚然,this在构造函数中让“escape”通常不是一个好主意,但它经常比替代方案更干净。

于 2012-06-26T18:58:49.633 回答
4

// 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();
}
于 2012-06-26T18:59:17.577 回答
3

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.

于 2012-06-26T18:58:58.893 回答
1
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);
}
于 2012-06-26T18:59:42.787 回答