我的班级使用第三方图书馆班来完成工作。通常我初始化第三方库类,它反过来触发回调方法:
public class MyJob {
private Thread myThread;
private ThirdPartyService mThirdParty;
public MyJob() {…}
public void start() {
//get an instance of 3rd party class
mThirdParty = ThirdParty.getInstance();
//create an instance of 3rd party callback
ThirdPartyCallBack callback = new ThirdPartyCallBack() {
@Override
public void onInitSuccess() {
if (null == myThread) {
myThread = new Thread();
System.out.println(“myThread is created in callback!”);
//do tasks…
}
}
};
System.out.println(“mThirdParty.init() …”);
mThirdParty.init(callback);
//myThread is null here when call start() the 2nd time, why?
if (myThread == null) {
System.out.println(“After mThirdParty.init(), myThread is NULL!”);
} else {
System.out.println(“After mThirdParty.init(), myThread is NOT NULL!”);
}
}
public void stop() {
myThread.join();
myThread = null;
System.out.println(“stopped!”);
}
}
如上所述,mThirdParty.init(callback)
会触发执行回调方法onInitSuccess()
。
代码使用MyJob类:
MyJob job = new MyJob();
job.start();
Thread.sleep(5000);
job.stop();
Thread.sleep(5000);
job.start();
我第一次开始工作,这里的每件事情都很好,控制台会打印以下日志:
mThirdParty.init() …
myThread is created in callback!
After mThirdParty.init(), myThread is NOT NULL!
5秒后,我调用stop(),日志显示:
stopped!
5秒后,再次开始工作,日志显示:
mThirdParty.init() …
myThread is created in callback!
After mThirdParty.init(), myThread is NULL!
为什么我第二次开始工作后,我的myThread是NULL?可能是第三方库已经以某种方式隐式地将其设置为null吗?
答案 0 :(得分:0)
好的,“第三方库”是您自己的代码。
public void stop() {
myThread.join();
myThread = null;
System.out.println(“stopped!”);
}
调用stop()时将其设置为null。
好像你有内存同步问题。将volatile
添加到myThread
。
private volatile Thread myThread