我有2个类(1个是基本类,第二个扩展了Thread类),并且我试图使用run()
访问在setText()
上的线程类中初始化的对象(类)
public class TThread extends Thread{
Patcher pf;
public TThread(String string) {
setName(string);
start();
}
@Override
public void run() {
pf = new Patcher("Checking Serial key..."); //<=== Class initialized here in a separate thread
}
public void setText(String string) {
pf.setText(string); //<=== Trying to access patcher here, throws NullPointerException
}
}
这就是我所说的
TThread
public void myCall(){
TThread tpf = new TThread("pf thread");
//some code later
try{
tpf.setText("blabla");
}
当我尝试从另一个线程访问修补程序时,
pf.setText()
会引发NullPointerException
。我怎样才能从另一个类或该类访问该线程并访问修补程序?
最佳答案
这是经典的比赛条件。因为您有两个线程,所以不能保证先发生什么。 pf
可能在被后台线程初始化之前被主线程访问。
现在,您的程序是不可预测的。尝试在Thread.sleep(100);
方法的开头添加setText
。它似乎可以正常工作,但在某些特定情况下仍可能失败。
解决此问题的一种方法是在主线程中等待,直到初始化pf
:
@Override
public synchronized void run() {
pf = new Patcher("Checking Serial key...");
notifyAll();
}
public synchronized void setText(String string) throws InterruptedException {
while(pf==null) {
wait();
}
pf.setText(string);
}
小心。如果您以前没有使用过线程,那么正确可能会很棘手。
关于java - 从另一个线程访问对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23848518/