【发布时间】:2013-05-21 21:53:46
【问题描述】:
我正在编写一个教育数学游戏,如果您可以同时选择许多操作,现在我尝试生成 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 和线程的新手,所以请耐心等待。 在此先感谢,并为我糟糕的英语感到抱歉。
【问题讨论】:
-
我没有看细节,但一个明显的问题是
this.wait中的this与this.notify中的this不是同一个对象(它是前者中的线程和后者中的 OnClickListener)。 -
在创建 onclicklistener 之前你还要等待,所以你的线程会卡在那个等待线上,永远没有机会调用 notify。而且您只能在同步块内调用等待和通知...