首页 > 解决方案 > 我如何引用来自不同线程java的方法

问题描述

我正在尝试从线程 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();
    }
}

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

标签: javamultithreadingconcurrencyjava.util.concurrent

解决方案


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

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

推荐阅读