Basic concepts of 1.JAVA threads:
Two ways to implement a thread:
(1) Inherit thread this class (the object represents a thread)
(2) Implement the Runnable interface (the object represents a thread body)
The life cycle of a thread:
Create
Generates a thread object;
Start method, ready;
Preemptive CPU operation;
The CPU is preempted by other threads or blocked and re-ready;
Execution completed;
A state of death that cannot be resurrected after death;
Android: Child threads in principle do not allow UI components to be modified, only the main thread can modify the UI components
2. Interface settings and component introduction:
Private button button; Private TextView TextView; @Override protectedvoid onCreate (Bundle savedinstancestate) { super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); TextView=(TextView) Findviewbyid (R.id.textview); Button=(Button) Findviewbyid (R.id.button); Button.setonclicklistener (new Buttonlistener ()); }
3. Creating and modifying sub-threads View:
classButtonlistener implements view.onclicklistener{@Override Public voidOnClick (view view) {MyThread T=NewMyThread ();//generating child threads in the main threadT.start (); } } classMyThread extends thread{@Override Public voidrun () {//Super.run (); Try{CurrentThread (). Sleep ( -); } Catch(interruptedexception e) {e.printstacktrace (); } textview.settext ("This one is a modification from a sub-thread"); } }
4. Modify the view in the main thread:
2017.12.18 Android Development Process explained