我如何从不同的线程java引用一个方法

时间:2018-04-24 15:07:43

标签: java multithreading concurrency java.util.concurrent

我试图从线程b引用线程a,我基本上想在B类/线程中使用getN()方法,感谢任何帮助

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

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

1 个答案:

答案 0 :(得分:2)

为了构造B类的对象,您需要引用A类的对象,而不是类Thread的对象。所以这应该有效:

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