0
嗨我正在嘗試製作一個多人遊戲,它會在另一個線程中找到對手,但我不確定爲什麼在線程中運行的代碼不會更新主類...如何更新線程中主類中的內容
這是主類中的代碼。到LoadTask調用啓動另一個線程
// Start model, passing number of words, user name, and selected animal
model = new MultiPlayerModel(NUM_WORDS, username, anmID);
model.addObserver(this);
new LoadTask().execute();
setContentView(R.layout.activity_multi_player);
initialDisplay(animal, background, oppAnimal);
下面是Thread類
private class LoadTask extends AsyncTask<Void, Integer, Void> {
// called before running code in a separate thread
private boolean quitFlag;
@Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(MultiPlayer.this,"Finding a Game...",
"Searching for opponent, please wait...", false, false);
}
@Override
protected Void doInBackground(Void... params) {
synchronized (this) {
try {
model.beginMatchMaking();
model.setWordsList();
// Get the opponent's animal from the model
oppAnimal = reverseDrawable(model.getOpponentAnimal());
// Display the multiplayer screen
} catch (InternetConnectionException e) {
e.fillInStackTrace();
quitFlag = true;
error(States.error.CONNECTION);
return null;
} catch (EmptyQueueException e) {
e.fillInStackTrace();
quitFlag = true;
error(States.error.NOOPPONENT);
return null;
} catch (InternalErrorException e) {
e.fillInStackTrace();
quitFlag = true;
error(States.error.INTERNAL);
return null;
}
}
return null;
}
@Override
protected void onPostExecute(Void result) {
if (!quitFlag) {
progressDialog.dismiss();
gameTimer = new GameTimer(START_TIME, INTERVAL);
gameTimer.start();
}
}
}
代碼,它initialDisplay出現segfaults線程調用後,因爲在模型類中的字段在未更新所有。它充當雖然它剛創建並沒有採取任何它
Ø確定,所以你說,這是行不通的,因爲並行運行,所以可能無法獲得主類在它之前更新線程。無論如何要讓主線程等到另一個完成? – James
最簡單的方法就是不要使用線程,如果你只需要等到它完成 - 使用簡單的方法調用。 但在一般情況下,您可能會使用monitor/wait/notify或CountDownLatch方法 – IvanNik
,所以我需要在一個線程中執行此操作的原因是我希望它顯示一個進度條,而不是黑屏。即使我做Thread.sleep(100)和CountDownLatch它仍然segfaults ...任何想法 – James