java 一个线程如何访问其他方法_如何从java中另一个正在运行的线程访问一个方法...

我是

Java Threads的新手.我想要做的是从ThreadB对象获得对当前运行的线程(ThreadA)的实例的访问,并调用其名为setSomething的方法.

1)我认为我比实际做得更努力

2)我有一个空指针异常,因此访问该方法时我必须做错事

这是我到目前为止所做的,我已经完成了尽职调查,并在StackOverflow上查看了类似的问题.

我有一个当前的Thread在后台运行:

// 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 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**

}

}

先感谢您

艾伦

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值