我正在写一个教育数学游戏,你可以同时选择许多操作,现在我试图生成 5 个问题,但是它运行所有五个问题的速度太快了,除了最后一个问题,我无法回答它们,因为它被卡在那里。所以我考虑创建一个线程,在创建第一个问题后等待()并等待它被解决并正确回答,然后继续下一个问题等等......现在我之前从未使用过等待和通知所以在哪里我应该在这里分配他们到目前为止我得到的东西,但是它给了我一个例外:
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 和线程的新手,所以请耐心等待我。在此先感谢并为我糟糕的英语感到抱歉。