wait() and notify() in a thread android -
im writing educational mathematics game can choose many operations @ same time, im trying generate 5 questions, runs 5 questions soo fast cant answer them except last questions because stuck there. thought creating thread wait() after creating first question , wait till solved , answered correctly, proceed next question , on... have never used wait , notify before should assign them here got far, gives me exception:
while (counter < 5) { thread pause = new thread() { @override public void run() { try { this.wait(); } catch (interruptedexception e) { e.printstacktrace(); } finally{ // ops array knowing operation chose, // 1 plus , 2 minus //generate random number within range of operations length. int gen = integer.valueof((int) ((math.random() * (ops.length)))); log.d("testgen", string.valueof(gen)); //random operation generated int thechosenoperation = ops[gen]; log.d("test chosen", string.valueof(thechosenoperation)); switch (thechosenoperation) { case 1: // if plus, assign generated numbers , j plus.java toast t = toast.maketext(secondactivity.this, "plus", 5000); t.show(); tv.settext("+"); int = plus.getborder(); int j = plus.getborder2(); tv2.settext(string.valueof(i)); tv3.settext(string.valueof(j)); answer = plus.getanswer(); break; case 2: //if minus, assign generated numbers , j 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 answer true notify() } else { toast t = toast.maketext(secondactivity.this, "false", 5000); t.show(); } } }); // end of clicklistner counter++; // counting 5 questions }//finally }//run }; // end of thread pause.start(); } //end of while loop
im still new android , threads please patient me. in advance , sorry horrible english.
the usage of thread
in context not correct.
- there's main thread or ui thread responsible presenting , managing ui state. if want make changes ui elements
textview
,button
, etc., you'll have in thread. if keep long duration tasks in thread or make thread wait, application become unresponsive , android os show anr dialog. (read more in keeping app responsive) thread
s used when there concurrent tasks executed. in case, tasks not concurrent, rather sequential.
you should think more in terms of event-driven approach application takes decision based on events (like question answered, can used check how many questions have been answered decide whether need generate more questions).
Comments
Post a Comment