In the development process today, we need to add multi-threaded operation to the previous program to avoid Networrk on Mainthread.
Because of the complexity of the code, the variables need to be fetched in the thread of the previous code, and the synchronization of the threads is critical
I know that the method of thread synchronization is mostly Thread.Join (), waiting for another thread to finish before continuing with the work of this thread.
However, in Android, Mainthread controls the refresh of the screen, and calling join in the main thread causes the screen to fail to refresh.
So, we can use this thread to wait for the end of a thread, and then refresh it by notifying the screen via the Runonuithread method after the wired thread has finished.
This is our time consuming thread (simulation runs for 3 seconds):
Thread1=new Thread (New Runnable () {@Overridepublic void Run () {//TODO auto-generated method stubtry {thread.sleep (3000); } catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}); Thread1.start ();
This is the notification thread:
New Thread (New Runnable () {@Overridepublic void Run () {//TODO auto-generated method stubtry {thread1.join ()} catch (Inte Rruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} Runonuithread (New Runnable () {public void run () {tv2.settext ("Tread complete!");}}). Start ();
In order to be able to visually see the effect, we can add this code on the basis of the previous TimerThread source, we can see that even when the Thread1 run, the UI thread can still be updated.
SOURCE is here: →http://download.csdn.net/detail/edwardwayne/8697147
Android multithreaded development keep clear sequence practice