在多线程编程这块,我们经常要使用Handler(处理),Thread(线程)和Runnable这三个类,那么他们之间的关系你是否弄清楚了呢?
First of all, the Android CPU allocation of the smallest unit is a thread, handler is generally created in a line thread, so handler and thread are bound to each other, one by one.
While Runnable is an interface, thread is a subclass of runnable. So, they're both a process.
Handlerthread, as the name implies, is a thread that can handle a message loop, a thread that has looper and can handle the message loop.
Instead of handler and a thread binding, it is better to say that handler is corresponding to Looper one by one.
Handler is the bridge between activity and thread/runnable. While handler is running in the main UI thread, it and the child thread can pass the data through the Message object
1, the first method of enabling is to implement a thread by inheriting the thread class and overwriting the Run method
public class MyThread extends Thread { //继承Thread类,并改写其run方法 private final static String TAG = "My Thread ===> "; public void run(){ Log.d(TAG, "run"); for(int i = 0; i<100; i++) { Log.e(TAG, Thread.currentThread().getName() + "i = " + i); } } }
Start
new MyThread().start();
2, second enable mode to create a Runnable object
public class myrunnable implements Runnable{ Span class= "Hljs-keyword" >private final static String TAG = Span class= "hljs-string" > "My Runnable ===>"; @Override public void run () {//TODO auto-generated Method Stub log.d (TAG, " run "); for (int i = 0; I<1000; i++) {log.e (TAG, Thread.CurrentThread (). GetName () + "i =" + i);}}}
Start
new Thread(new MyRunnable()).start();
Another way to enable
btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new Thread(new Runnable() { @Override public void run() { try { ... } catch (Exception e) { e.printStackTrace(); } } }).start(); } });
3, the third enabled way to start a thread through handler
PublicClassMainactivityExtendsActivity {PrivateFinalstatic String TAG ="Uofly Android Thread ==>";Privateint count =0;Private Handler Mhandler =New Handler ();Private Runnable mrunnable =New Runnable () {PublicvoidRun () {LOG.E (TAG, Thread.CurrentThread (). GetName () +"" + count); count++; Settitle ("" + count);//every 3 seconds mhandler.postdelayed (mrunnable, 3000); //to send themselves a message, self-running}}; /** called when the activity is first created. */ @Override Span class= "Hljs-keyword" >public void oncreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.main ); //through handler boot thread mhandler.post (mrunnable); //send message, start thread run} @Override protected void Span class= "Hljs-title" >ondestroy () {//the thread is destroyed mhandler.removecallbacks (mRunnable); Span class= "Hljs-keyword" >super.ondestroy (); } }
Three threads-enabled methods in Android