[英]How to access a method from another running thread in java
我是 Java 线程的新手。 我想要做的是从 ThreadB 对象获得对当前正在运行的线程 ThreadA 的实例的访问权限,并调用其名为 setSomething 的方法。 1)我认为我做得比实际更难 2)我有一个空指针异常,所以在访问该方法时我一定是做错了什么
这是我到目前为止所做的,我已经完成了尽职调查,并在 StackOverflow 上查看了类似的问题。
我有一个在后台运行的当前线程:
// assume this thread is called by some other application
public class ThreadA implements Runnable{
private Thread aThread;
public ThreadA(){
aThread = new Thread(this);
aThread.setName("AThread");
aThread.start();
}
@Override
public void run(){
while(true){
// doing something
}
}
public void setSomething(String status){
// process something
}
}
// assume this thread is started by another application
public class ThreadB implements Runnable{
@Override
public void run(){
passAValue("New");
}
public void passAValue(String status){
// What I am trying to do is to get the instance of ThreadA and call
// its method setSomething but I am probably making it harder on myself
// not fully understanding threads
Method[] methods = null;
// get all current running threads and find the thread i want
Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
for(Thread t : threadSet){
if(t.getName().equals("AThread")){
methods = t.getClass().getMethods();
}
}
//**How do I access ThreadA's method, setSomething**
}
}
提前谢谢你
艾伦
哇,你为什么把事情搞得这么复杂?! 这并不像你想象的那么难(在黑暗城堡中杀死一条龙!)
好的,您需要做的就是将 threadA 引用传递给 threadB! 就这个。 让我说,当您从线程 b 调用方法时,它由线程 b 运行,而不是托管该类。
class ThreadA implements Runnable {
public void run() {
//do something
}
public void setSomething() { }
}
class ThreadB implements Runnable {
private ThreadA aref;
public ThreadB(ThreadA ref) { aref = ref; }
public void run() {
aref.setSomething(); // Calling setSomething() with this thread! (not thread a)
}
}
class Foo {
public static void main(String...arg) {
ThreadA a = new ThreadA();
new Thread(a).start();
ThreadB b = new ThreadB(a);
new Thread(b).start();
}
}
这里有一个简单的线程教程
在实例化 ThreadB 对象时或之后,为其提供对 ThreadA 对象实例的引用。 类似的东西:
ThreadA a = new ThreadA();
ThreadB b = new ThreadB(a);
然后,在 ThreadB 代码中,您可以使用毫无疑问存储在 ThreadB 中的实例变量中的引用来调用 ThreadA 的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.