
為什麼遊戲開發離不開多線程
做過Android開發的人大概都踩過這個坑:當主線程被阻塞超過5秒,系統就會彈出「應用程序無響應」的提示,這就是所謂的ANR(Application Not Responding)。善用多線程能有效避開ANR,但要注意別走極端——並非線程越多越好。真正值得丟到子線程裡的,是那些明顯耗時的操作,比如訪問網絡接口返回緩慢、加載大量數據導致列表滑動卡頓、讀取體積龐大的I/O資源等等。把這些重活交給新線程,主線程才能保持流暢。
不過多線程是把雙刃劍。線程一多,數據同步問題就跟著上門,需要開發者細心處理。因此設計時應盡量讓各線程各司其職、互不干擾。Java提供了 synchronized 這個「線程鎖」的概念,可以為對象或方法上鎖,避免多個線程同時訪問同一資源引發的衝突,有興趣的讀者不妨深入了解一下。
1. Thread 與 Handler 執行多線程

Handler的核心作用,是在主線程與我們自建的子線程之間搭起通信的橋樑。下面的例子演示了這樣一個場景:點擊按鈕後開啟一個新線程,循環加載100張圖片,每加載完一張就通過Handler給UI線程發一條消息更新進度;全部加載完畢後,再通知UI顯示總耗時。Handler在這裡扮演的角色,就是那座連接兩個世界的橋。
Java代碼
- import java.io.InputStream;
-
- import android.app.Activity;
- import android.content.Context;
- import android.graphics.Bitmap;
- import android.graphics.BitmapFactory;
- import android.os.Bundle;
- import android.os.Handler;
- import android.os.Message;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.TextView;
-
- public class SingleActivity extends Activity {
-
- /**讀取進度**/
- public final static int LOAD_PROGRESS = 0;
-
- /**標志讀取進度結束**/
- public final static int LOAD_COMPLETE = 1;
-
- /** 開始加載100張圖片按鈕 **/
- Button mButton = null;
- /** 顯示內容 **/
- TextView mTextView = null;
- /** 加載圖片前的時間 **/
- Long mLoadStatr = 0L;
- /** 加載圖片後的時間 **/
- Long mLoadEnd = 0L;
-
- Context mContext = null;
-
- //接收傳遞過來的信息
- Handler handler = new Handler() {
- @Override
- public void handleMessage(Message msg) {
- switch (msg.what) {
- case LOAD_PROGRESS:
- mTextView.setText("當前讀取到第" + msg.arg1 + "張圖片");
- break;
- case LOAD_COMPLETE:
- mTextView.setText("讀取結束一共耗時" + msg.arg1 + "毫秒");
- break;
- }
- super.handleMessage(msg);
- }
- };
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- setContentView(R.layout.single);
- mContext = this;
-
- /** 拿到button 與 TextView 對象 **/
- mButton = (Button) findViewById(R.id.button0);
- mTextView = (TextView) findViewById(R.id.textView0);
- mTextView.setText("點擊按鈕開始更新時間");
- mButton.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View arg0) {
- //開始讀取圖片
- LoadImage();
- }
- });
-
- super.onCreate(savedInstanceState);
- }
-
- public void LoadImage() {
- new Thread() {
- @Override
- public void run() {
- //得到加載圖片開始的時間
- mLoadStatr = System.currentTimeMillis();
-
- for (int i = 0; i < 100; i++) {
- // 這裡循環加載圖片100遍
- ReadBitMap(mContext, R.drawable.bg);
-
- // 每讀取完一張圖片將進度甩給handler
- Message msg = new Message();
- msg.what = LOAD_PROGRESS;
- msg.arg1 = i + 1;
- handler.sendMessage(msg);
- }
-
- //得到加載圖片結束的時間
- mLoadEnd = System.currentTimeMillis();
-
- //100張圖片加載完成
- Message msg = new Message();
- msg.what = LOAD_COMPLETE;
- msg.arg1 = (int) (mLoadEnd - mLoadStatr);
- handler.sendMessage(msg);
- }
- }.start();
-
- }
-
- /**
- * 讀取本地資源的圖片
- *
- * @param context
- * @param resId
- * @return
- */
- public Bitmap ReadBitMap(Context context, int resId) {
- BitmapFactory.Options opt = new BitmapFactory.Options();
- opt.inPreferredConfig = Bitmap.Config.RGB_565;
- opt.inPurgeable = true;
- opt.inInputShareable = true;
- // 獲取資源圖片
- InputStream is = context.getResources().openRawResource(resId);
- return BitmapFactory.decodeStream(is, null, opt);
- }
- }
2. TimerTask 與 Handler 實現延遲多線程

Timer 與 TimerTask 組合起來就是一個定時器,相當於開啟一個線程,每隔指定的時間間隔執行一次任務。這個定時線程也可以隨時關閉。舉個實際例子:做網游的登錄超時檢測時,用戶輸入帳號密碼點擊登錄後,我們開啟一個TimerTask,每秒檢查一次是否登錄成功,若10秒後仍未成功便提示「登錄超時」。任務完成後,就需要在檢測線程中調用 cancel() 把Timer與TimerTask關掉,避免它繼續空轉。下面的例子完整演示了這一流程。
Java代碼
- import java.util.Timer;
- import java.util.TimerTask;
- import android.app.Activity;
- import android.content.Context;
- import android.os.Bundle;
- import android.os.Handler;
- import android.os.Message;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.TextView;
-
- public class TimerTaskActivity extends Activity {
-
- /**執行Timer進度**/
- public final static int LOAD_PROGRESS = 0;
-
- /**關閉Timer進度**/
- public final static int CLOSE_PROGRESS = 1;
-
- /** 開始TimerTask按鈕 **/
- Button mButton0 = null;
-
- /** 關閉TimerTask按鈕 **/
- Button mButton1 = null;
-
- /** 顯示內容 **/
- TextView mTextView = null;
-
- Context mContext = null;
-
- /**Timer對象**/
- Timer mTimer = null;
-
- /**TimerTask對象**/
- TimerTask mTimerTask = null;
-
- /**記錄TimerID**/
- int mTimerID = 0;
-
- /**接收傳遞過來的信息**/
- Handler handler = new Handler() {
- @Override
- public void handleMessage(Message msg) {
- switch (msg.what) {
- case LOAD_PROGRESS:
- mTextView.setText("當前TimerID為" + msg.arg1 );
- break;
- case CLOSE_PROGRESS:
- mTextView.setText("當前Timer已經關閉請重新開啟" );
- break;
-
- }
- super.handleMessage(msg);
- }
- };
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- setContentView(R.layout.timer);
- mContext = this;
-
- /** 拿到button 與 TextView 對象 **/
- mButton0 = (Button) findViewById(R.id.button0);
- mButton1 = (Button) findViewById(R.id.button1);
- mTextView = (TextView) findViewById(R.id.textView0);
- mTextView.setText("點擊按鈕開始更新時間");
-
- //開始
- mButton0.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View arg0) {
- //開始執行timer
- StartTimer();
- }
- });
-
- //關閉
- mButton1.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View arg0) {
- //停止執行timer
- CloseTimer();
- }
- });
-
- super.onCreate(savedInstanceState);
- }
-
- public void StartTimer() {
-
- if (mTimer == null) {
- mTimerTask = new TimerTask() {
- public void run() {
- //mTimerTask與mTimer執行的前提下每過1秒進一次這裡
- mTimerID ++;
- Message msg = new Message();
- msg.what = LOAD_PROGRESS;
- msg.arg1 = (int) (mTimerID);
- handler.sendMessage(msg);
- }
- };
- mTimer = new Timer();
-
- //第一個參數為執行的mTimerTask
- //第二個參數為延遲的時間 這裡寫1000的意思是mTimerTask將延遲1秒執行
- //第三個參數為多久執行一次 這裡寫1000表示每1秒執行一次mTimerTask的Run方法
- mTimer.schedule(mTimerTask, 1000, 1000);
- }
-
- }
-
- public void CloseTimer() {
-
- //在這裡關閉mTimer 與 mTimerTask
- if (mTimer != null) {
- mTimer.cancel();
- mTimer = null;
- }
- if (mTimerTask != null) {
- mTimerTask = null;
- }
-
- /**ID重置**/
- mTimerID = 0;
-
- //這裡發送一條只帶what空的消息
- handler.sendEmptyMessage(CLOSE_PROGRESS);
- }
- }
3. AsyncTask 執行多線程

AsyncTask把異步流程拆成了幾個環節,執行順序一目了然:
onPreExecute()——最先執行,運行在UI線程中,適合做一些初始化準備;
doInBackground(Object... arg0)——真正的後台異步執行體,跑完後可以返回一個結果對象;
onProgressUpdate()——用來更新界面進度,需要在doInBackground中手動調用 publishProgress() 觸發;
onPostExecute(Object result)——在後台任務結束後接收最終結果。
下面的例子同樣計算加載100張圖片的耗時。就純執行效率而言,AsyncTask未必比Thread更快,但它勝在結構清晰、規整,能隨時拿到異步進度與最終結果,讓代碼可讀性更好。可以這樣理解:Thread能做的事,AsyncTask基本都能做;而AsyncTask能優雅完成的進度回調與結果返回,用Thread硬做往往很笨拙。我的建議是——大批量、需要回調的異步任務優先選AsyncTask,零散的小任務則用Thread即可。
Java代碼
- import java.io.InputStream;
- import java.util.Timer;
- import java.util.TimerTask;
- import android.app.Activity;
- import android.content.Context;
- import android.graphics.Bitmap;
- import android.graphics.BitmapFactory;
- import android.os.AsyncTask;
- import android.os.Bundle;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.TextView;
-
- public class AsyncTaskActivity extends Activity {
-
- /**執行Timer進度**/
- public final static int LOAD_PROGRESS = 0;
-
- /**關閉Timer進度**/
- public final static int CLOSE_PROGRESS = 1;
-
- /** 開始StartAsync按鈕 **/
- Button mButton0 = null;
-
- /** 顯示內容 **/
- TextView mTextView = null;
-
- Context mContext = null;
-
- /**Timer對象**/
- Timer mTimer = null;
-
- /**TimerTask對象**/
- TimerTask mTimerTask = null;
-
- /**記錄TimerID**/
- int mTimerID = 0;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- setContentView(R.layout.async);
- mContext = this;
-
- /** 拿到button 與 TextView 對象 **/
- mButton0 = (Button) findViewById(R.id.button0);
- mTextView = (TextView) findViewById(R.id.textView0);
- //開始
- mButton0.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View arg0) {
- //開始執行StartAsync
- StartAsync();
- }
- });
-
- super.onCreate(savedInstanceState);
- }
-
- public void StartAsync() {
- new AsyncTask<Object, Object, Object>() {
-
- @Override
- protected void onPreExecute() {
- //首先執行這個方法,它在UI線程中 可以執行一些異步操作
- mTextView.setText("開始加載進度");
- super.onPreExecute();
- }
-
- @Override
- protected Object doInBackground(Object... arg0) {
- //異步後台執行 ,執行完畢可以返回出去一個結果object對象
-
- //得到開始加載的時間
- Long startTime = System.currentTimeMillis();
- for (int i = 0; i < 100; i++) {
- // 這裡循環加載圖片100遍
- ReadBitMap(mContext, R.drawable.bg);
- //執行這個方法會異步調用onProgressUpdate方法,可以用來更新UI
- publishProgress(i);
- }
- //得到結束加載的時間
- Long endTime = System.currentTimeMillis();
-
- //將讀取時間返回
- return endTime - startTime;
- }
-
- @Override
- protected void onPostExecute(Object result) {
- //doInBackground之行結束以後在這裡可以接收到返回的結果對象
-
- mTextView.setText("讀取100張圖片一共耗時" + result+ "毫秒");
-
- super.onPostExecute(result);
- }
-
- @Override
- protected void onProgressUpdate(Object... values) {
- //時時拿到當前的進度更新UI
-
- mTextView.setText("當前加載進度" + values[0]);
- super.onProgressUpdate(values);
- }
- }.execute();//可以理解為執行 這個AsyncTask
-
- }
- /**
- * 讀取本地資源的圖片
- *
- * @param context
- * @param resId
- * @return
- */
- public Bitmap ReadBitMap(Context context, int resId) {
- BitmapFactory.Options opt = new BitmapFactory.Options();
- opt.inPreferredConfig = Bitmap.Config.RGB_565;
- opt.inPurgeable = true;
- opt.inInputShareable = true;
- // 獲取資源圖片
- InputStream is = context.getResources().openRawResource(resId);
- return BitmapFactory.decodeStream(is, null, opt);
- }
- }
4. 多線程中 Looper 的使用

Looper負責管理線程的消息隊列與消息循環。在Handler中,默認使用的是主線程的mainLooper;但如果在一個全新的子線程裡創建Handler,由於該線程沒有現成的Looper,程序就會拋出異常。這時需要手動調用 Looper.prepare() 為當前線程建立消息隊列,再調用 Looper.loop() 啟動消息循環,這個子線程才算具備了處理消息的能力。下面的例子演示了這一過程,值得仔細研讀。
Java代碼
- import java.io.InputStream;
-
- import android.app.Activity;
- import android.content.Context;
- import android.graphics.Bitmap;
- import android.graphics.BitmapFactory;
- import android.os.Bundle;
- import android.os.Handler;
- import android.os.Looper;
- import android.os.Message;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.Toast;
-
- public class LooperActivity extends Activity {
- /** 發送消息按鈕 **/
- Button mButton = null;
- /** 加載圖片前的時間 **/
- Long mLoadStatr = 0L;
- /** 加載圖片後的時間 **/
- Long mLoadEnd = 0L;
-
- Context mContext = null;
-
- private Handler handler = new Handler() {
- public void handleMessage(Message msg) {
- new Thread() {
- @Override
- public void run() {
-
- //如果handler不指定looper的話
- //默認為mainlooper來進行消息循環,
- //而當前是在一個新的線程中它沒有默認的looper
- //所以我們須要手動調用prepare()拿到他的loop
- //可以理解為在Thread創建Looper的消息隊列
- Looper.prepare();
-
- Toast.makeText(LooperActivity.this, "收到消息",Toast.LENGTH_LONG).show();
-
- //在這裡執行這個消息循環如果沒有這句
- //就好比只創建了Looper的消息隊列而
- //沒有執行這個隊列那麼上面Toast的內容是不會顯示出來的
- Looper.loop();
-
- //如果沒有
- //Looper.prepare(); 與 Looper.loop();
- //會拋出異常Can't create handler inside thread that has not called Looper.prepare()
- //原因是我們新起的線程中是沒有默認的looper所以須要手動調用prepare()拿到他的loop
-
- }
- }.start();
- }
- };
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- setContentView(R.layout.loop);
- mContext = this;
-
- /** 拿到button 與 TextView 對象 **/
- mButton = (Button) findViewById(R.id.button0);
- mButton.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View arg0) {
- new Thread() {
- @Override
- public void run() {
-
- //發送一條空的消息
- //空消息中必需帶一個what字段
- //用於在handler中接收
- //這裡暫時我先寫成0
- handler.sendEmptyMessage(0);
-
- }
- }.start();
- }
- });
-
- super.onCreate(savedInstanceState);
- }
- /**
- * 讀取本地資源的圖片
- *
- * @param context
- * @param resId
- * @return
- */
- public Bitmap ReadBitMap(Context context, int resId) {
- BitmapFactory.Options opt = new BitmapFactory.Options();
- opt.inPreferredConfig = Bitmap.Config.RGB_565;
- opt.inPurgeable = true;
- opt.inInputShareable = true;
- // 獲取資源圖片
- InputStream is = context.getResources().openRawResource(resId);
- return BitmapFactory.decodeStream(is, null, opt);
- }
- }
源碼下載地址:https://vdisk.weibo.com/s/aakLw