Search code examples
javamultithreadingconcurrencyjava.util.concurrent

How do i reference a method from a different threads java


I'm trying to reference thread a from thread b, I essentially want to use the getN() method in B class/thread, any help is appreciated

//// class help {
    ///// main {

        Thread a = new Thread(new A());
        Thread b = new Thread(new B(a));
    }
}

class A implements Runnable {
    private static int tally;
    public void run() {

    }
    public int getN() {
        tally = 6;
        return tally;
    }
}

class B implements Runnable {
    private A aref;
    public B(A ref){
        aref=ref;
    }
    public void run() {
        aref.getN();
    }
}

////////////////////////////////////////////////////////////////// /////////////////////////


Solution

  • In order to construct an object of class B you need a reference to object of class A, not to the object of class Thread. So this should work:

    A objA = new A();
    Thread a = new Thread(objA);
    Thread b = new Thread(new B(objA));