java handler null_java – 在调用之前,如何确保另一个Thread的Handler不为null?
有一天,當我試圖使用在另一個線程上創建的Handler向該線程發送消息時,我的程序拋出了NullPointerException.盡管調用線程已經在另一個線程上調用了start,但是另一個線程創建的Handler尚未創建,或者尚未對調用線程可見.這種情況很少發生.幾乎每次測試都沒有得到例外.
我想知道什么是最好的方法來避免這個問題,確保最小的復雜性和性能損失.該程序是一款游戲,性能非常敏感,特別是一旦運行.因此,我嘗試避免在設置后使用同步,例如,并且寧愿在任何時候避免旋轉變量.
必須在將使用它的線程上創建處理程序.因此,在創建該線程的線程運行的線程的構造函數中創建它不是一個選項.
該文檔給出了為此目的使用這兩個類的示例:
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();
}
}
我非常丑陋的解決方案目前看起來像這樣:
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.
}
}
}
}
使用創建線程中的代碼如下所示:
LooperThread otherThread = new LooperThread();
otherThread.start();
otherThread.waitForSetupComplete();
otherThread.mHandler.sendEmptyMessage(0);
還有更好的解決方案嗎?謝謝.
總結
以上是生活随笔為你收集整理的java handler null_java – 在调用之前,如何确保另一个Thread的Handler不为null?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 股票688开头怎么买不了
- 下一篇: 年利率怎么算 分存款利率和贷款利率