android - Having fun with Threads -
i having troubles threading ;)
i have done script class follow:
class test{ texttospeech mtts = new texttospeech(); boolean volatile mvarglobal = false; class t1 extends thread{ public void run(){ dosomething(){ mvarglobal = false; // network working...take while mtts.speak(...) //speech information received network mvarglobal = true; } } t1 t = new t1(); t.start(); class checkvarglobal extends thread{ public void run(){ if(!mvarglobal) { text2speech.speak("something"); } postattime(this, 3000); } } checkvarglobal c = new checkvarglobal (); c.start();
}
as can see have 2 threads running, 1 getting network information , second 1 cheking if information network has been received. boolean variable mvarglobal true, , thread checking "checkvarglobal" stop condition (!mvarglobal) false.
the problem once information in 1st thread network , speech information, 2nd thread still running , speeching "something". guess 2nd thread has not realize checkvarglobal true... have typed variable volatile used 2 threads.
any idea why happening, , how solve it?
thanks lot,
best. david.
dayerman... here experimental code 2 handlers.
edit. have edited code comply best practices, using switch in single handler:
private handler myhandler= new handler(){ @override public void handlemessage(message msg){ switch(msg.what){ case 0: if (!isdonethinking){ edittextconfusedtext.settext("still thinking "+new integer(thinkseconds).tostring()); thinkseconds++; this.removemessages(0); sendmessagedelayed(obtainmessage(0),1000); } else { thinkseconds= 0; // reset timer } break; case 1: isdonethinking= true; onthreadedmessage(msg); break; default: super.handlemessage(msg); break; } } }; public void onthreadmessage(message msg){ bundle b= msg.getdata(); string encryptedtext=""; if (b != null){ encryptedtext= b.getstring("encryptedtext"); } edittextconfusedtext.settext(encryptedtext); log.d(tag,encryptedtext); }
usage:
buttonconfusetext.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { // todo auto-generated method stub final string instring= edittextplaintext.gettext().tostring(); isdonethinking= false; myhandler.sendemptymessage(0); // <=== start timer thread thread= new thread( new runnable() { // <== start threaded runnable public void run() { string outstring= encrypt(password,instring); message msg= myhandler.obtainmessage(1); bundle b= new bundle(); b.putstring("encryptedtext",outstring); msg.setdata(b); myhandler.sendmessage(msg); log.d(tag,outstring); } }); thread.setdaemon(true); thread.start(); } };
Comments
Post a Comment