我寫一個教育數學遊戲,你可以在同一時間選擇許多操作,現在即時試圖產生5個問題,但它運行所有五個問題太快,我不能回答他們,除了最後的問題,因爲它卡在那裏。所以我想創建一個線程,在創建第一個問題後等待(),然後等待它解決並正確回答,然後繼續下一個問題,等等......現在我從來沒有用過wait和notify,所以在那裏我應該爲它們分配 在這裏我得到了什麼,到目前爲止,但它給了我一個例外:等待()和通知()在一個線程android
while (counter < 5) {
Thread pause = new Thread() {
@Override
public void run() {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
} finally{
// ops array is for knowing what operation he chose,
// 1 for plus and 2 for minus
//generate random number within the range of the operations length.
int gen = Integer.valueOf((int) ((Math.random() * (ops.length))));
Log.d("Testgen", String.valueOf(gen));
//random operation is generated
int TheChosenOperation = ops[gen];
Log.d("Test The chosen", String.valueOf(TheChosenOperation));
switch (TheChosenOperation) {
case 1: // if it is plus, assign the generated numbers to i and j from plus.java
Toast t = Toast.makeText(SecondActivity.this, "Plus", 5000);
t.show();
tv.setText("+");
int i = plus.getBorder();
int j = plus.getBorder2();
tv2.setText(String.valueOf(i));
tv3.setText(String.valueOf(j));
answer = plus.getAnswer();
break;
case 2: //if it is minus, assign the generated numbers to i and j from minus.java
Toast t2 = Toast.makeText(SecondActivity.this, "minus", 5000);
t2.show();
tv.setText("-");
int i2 = minus.getBorder();
int j2 = minus.getBorder2();
tv2.setText(String.valueOf(i2));
tv3.setText(String.valueOf(j2));
answer = minus.getAnswer();
break;
}
b.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (answer > 0 && answer == Integer.parseInt(ed.getText().toString())) {
Toast t = Toast.makeText(SecondActivity.this, "true",
5000);
t.show();
this.notify(); // if the answer is true then notify()
} else {
Toast t = Toast.makeText(SecondActivity.this, "false",
5000);
t.show();
}
}
}); // end of clicklistner
counter++; // counting for 5 questions
}//finally
}//run
}; // end of thread
pause.start();
} //end of while loop
我還在新的Android和線程所以請耐心等待我。 提前致謝,並對我可怕的英語感到抱歉。
我沒有看過細節,但一個顯而易見的問題是'this.wait'中的'this'與'this.notify'中的'this'不是同一個對象(它是前者中的線程,後者中的OnClickListener)。 – assylias
同樣你在創建你的onclicklistener之前等待,所以你的線程會卡在這個等待線上,永遠不會有調用通知的機會。你只能在同步塊中調用wait和notify ... – assylias