我的課程使用第三方庫類來完成一項工作。一般來說,我初始化第三方庫類,這反過來又觸發回調方法:由於某種原因,線程變量被隱式設置爲空
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秒鐘後,我打電話停止(),日誌顯示:
stopped!
後5秒,再次啓動工作,日誌顯示:
mThirdParty.init() …
myThread is created in callback!
After mThirdParty.init(), myThread is NULL!
爲什麼在我第二次啓動工作之後,我的myThread是NULL?難道第三方庫已經以某種方式隱式地將其設置爲null?
你如何看待第三方庫的源代碼? –
這是真實的代碼嗎?因爲'myThread = new Thread();'是無用的。還是你在項目中創建了一個名爲Thread的類? –
它不是真正的代碼,我只是試圖展示我的代碼的一般邏輯 – user842225