gpt4 book ai didi

java - 如何从java中的另一个正在运行的线程访问方法

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:13:44 25 4
gpt4 key购买 nike

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

here一个简单的线程教程

关于java - 如何从java中的另一个正在运行的线程访问方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19500517/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com