java handler null_java – 在调用之前,如何确保另一个Thread的Handler不为null?
有一天,當(dāng)我試圖使用在另一個(gè)線程上創(chuàng)建的Handler向該線程發(fā)送消息時(shí),我的程序拋出了NullPointerException.盡管調(diào)用線程已經(jīng)在另一個(gè)線程上調(diào)用了start,但是另一個(gè)線程創(chuàng)建的Handler尚未創(chuàng)建,或者尚未對(duì)調(diào)用線程可見(jiàn).這種情況很少發(fā)生.幾乎每次測(cè)試都沒(méi)有得到例外.
我想知道什么是最好的方法來(lái)避免這個(gè)問(wèn)題,確保最小的復(fù)雜性和性能損失.該程序是一款游戲,性能非常敏感,特別是一旦運(yùn)行.因此,我嘗試避免在設(shè)置后使用同步,例如,并且寧愿在任何時(shí)候避免旋轉(zhuǎn)變量.
必須在將使用它的線程上創(chuàng)建處理程序.因此,在創(chuàng)建該線程的線程運(yùn)行的線程的構(gòu)造函數(shù)中創(chuàng)建它不是一個(gè)選項(xiàng).
該文檔給出了為此目的使用這兩個(gè)類的示例:
class LooperThread extends Thread {
public Handler mHandler;
public void run() {
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
}
};
Looper.loop();
}
}
我非常丑陋的解決方案目前看起來(lái)像這樣:
public class LooperThread extends Thread {
public volatile Handler mHandler;
public final ArrayBlockingQueue setupComplete = new ArrayBlockingQueue(1);
public void run() {
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
}
};
setupComplete();
Looper.loop();
}
public void waitForSetupComplete() {
while ( true ) {
try {
setupComplete.take();
return;
} catch (InterruptedException e) {
//Ignore and try again.
}
}
}
private void setupComplete() {
while( true ) {
try {
setupComplete.put(new Object());
return;
} catch (InterruptedException e) {
//Ignore and try again.
}
}
}
}
使用創(chuàng)建線程中的代碼如下所示:
LooperThread otherThread = new LooperThread();
otherThread.start();
otherThread.waitForSetupComplete();
otherThread.mHandler.sendEmptyMessage(0);
還有更好的解決方案嗎?謝謝.
總結(jié)
以上是生活随笔為你收集整理的java handler null_java – 在调用之前,如何确保另一个Thread的Handler不为null?的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 股票688开头怎么买不了
- 下一篇: go在方法中修改结构体的值_golang