2012-05-06 202 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){...} 
    } 
}