Android 中三種使用執行緒的方法
public class
Thread
There are basically two main ways of having aThread
execute application code. One is providing a new class that extendsThread
and
overriding itsrun()
method. The other is providing a newThread
instance
with aobject during its creation(提供給它的例項化). In both cases, themethod
must be called to actually execute the newThread
.
Thread
with noRunnable
object
and a newly generated name.
Constructs a newThread
with aRunnable
object
and a newly generated name.
在多執行緒程式設計這塊,我們經常要使用Handler,Thread和Runnable這三個類,那麼他們之間的關係你是否弄清楚了呢?
首先說明Android的CPU分配的最小單元是執行緒,Handler一般是在某個執行緒裡建立的,因而Handler和Thread就是相互繫結的,一一對應。
而Runnable是一個介面,Thread是Runnable的子類。所以說,他倆都算一個程序。
HandlerThread顧名思義就是可以處理訊息迴圈的執行緒,他是一個擁有Looper的執行緒,可以處理訊息迴圈。
與其說Handler和一個執行緒繫結,不如說Handler是和Looper一一對應的。
Handler是溝通Activity與Thread/runnable的橋樑。而Handler是執行在主UI執行緒中的,它與子執行緒可以通過Message物件來傳遞資料
1.通過繼承Thread類,並改寫run方法來實現一個執行緒
-
publicclass MyThread
- //繼承Thread類,並改寫其run方法
- privatefinalstatic String TAG = "My Thread ===> ";
- publicvoid run(){
- Log.d(TAG, "run");
- for(int i = 0; i<100; i++)
- {
- Log.e(TAG, Thread.currentThread().getName() + "i = " + i);
- }
- }
- }
啟動執行緒:
2.建立一個Runnable物件
- publicclass MyRunnable implements Runnable{
- privatefinalstatic String TAG = "My Runnable ===> ";
- @Override
- publicvoid 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);
- }
- }
- }
啟動執行緒:
- // providing a new Thread instance with a Runnable object during its creation.
- new Thread(new MyRunnable()).start();
3.通過Handler啟動執行緒
- publicclass MainActivity extends Activity {
- privatefinalstatic String TAG = "UOfly Android Thread ==>";
- privateint count = 0;
- private Handler mHandler = new Handler();
- private Runnable mRunnable = new Runnable() {
- publicvoid run() {
- Log.e(TAG, Thread.currentThread().getName() + " " + count);
- count++;
- setTitle("" + count);
- // 每3秒執行一次
- mHandler.postDelayed(mRunnable, 3000); //給自己傳送訊息,自執行
- }
- };
- /** Called when the activity is first created. */
- @Override
- publicvoid onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- // 通過Handler啟動執行緒
- mHandler.post(mRunnable); //傳送訊息,啟動執行緒執行
- }
- @Override
- protectedvoid onDestroy() {
- //將執行緒銷燬掉
- mHandler.removeCallbacks(mRunnable);
- super.onDestroy();
- }
-
}