嗨我正在尝试制作一个多人游戏,它会在另一个线程中找到对手,但我不确定为什么线程中运行的代码不会更新主类中的模型......
这是主类中的代码。调用 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);
这是线程类的代码
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 上出现段错误。它表现得好像它刚刚创建并且没有对其进行任何操作