2012-05-06 40 views
1

我正在實現我自己的SurfaceView,其中包含一個Thread對象,其目的是將各種圖形對象繪製到Canvas。在我的SurfaceView的構造函數中,我設置了要繪製的對象,並且Thread對象(當前)僅根據需要將它們放置到Canvas。HandlerThread如何處理消息?

我現在需要改變我的SurfaceView的構造函數創建的對象之一(對象是位圖)用戶執行特定的操作(即Thread對象正在運行)之後。這意味着應用程序的GUI線程和執行線程對象的線程之間的通信。我發現了this頁面,詳細介紹了HandlerThread類的使用,非常適合我需要實現的功能。不過,我需要確定這個類是如何工作的,以確保沒有內存一致性錯誤。

下面是我自己的類的僞代碼剝離出來清晰了很多:

public MyThread extends Thread { 
    boolean _run = true; 
    public void run(){ 

     // Create HandlerThread object 
     // Create Looper object 
     // Create Handler object 
     while (_run){ 
      // DRAW the Bitmap in this loop 
     } 
    } 

    public boolean handleMessage(Message message){ 
     /* 
     ALTER the Bitmap here as required 
     */ 
    } 
} 


public MyThread extends Thread { 
    boolean _run = true; 
    public void run(){ 

     // Create HandlerThread object 
     // Create Looper object 
     // Create Handler object 
     while (_run){ 
      // DRAW the Bitmap in this loop 
     } 
    } 

    public boolean handleMessage(Message message){ 
     /* 
     ALTER the Bitmap here as required 
     */ 
    } 
} 

據我瞭解的handleMessage()方法由同一個線程執行run()方法執行。但是因爲handleMessage() ALTERS位圖,而run()繪製位圖。在線程返回到run()方法之前,我能確定handleMessage()將完整完成嗎?

回答

0

不知道我是否理解這個問題?

你延長在兩種情況下,其本身不執行任何特殊規則的Thread類。進程以序列化方式執行,除非您另行指定runhandleMessage從不同的CALLING線程運行。所以我的猜測是肯定的。這應該是一個相當直接的線程安全執行模式 - 如果你在同一個線程中調用handleMessagerun,那麼沒有理由不應該同步它們。如果您從不同線程調用兩種方法(或者如果您非常擔心並且無法在其他任何地方找到答案),則可以通過在兩種方法中使用synchronized(myLock)鎖定對象監視器:

public MyThread extends Thread { 
    boolean _run = true; 
    public void run(){ 
     synchronized(this) { 
      while (_run){ 
      // DRAW the Bitmap in this loop 
      } 
     } 
    } 

    public boolean handleMessage(Message message){ 
     synchronized(this){...} 
    } 
}