1

我正在实现我自己的SurfaceView,它包含一个 Thread 对象,其目的是将各种图形对象绘制到 Canvas 上。在我的 SurfaceView 的构造函数中,我设置了要绘制的对象,并且 Thread 对象(当前)仅将它们适当地定位到 Canvas。

在用户执行特定操作(即线程对象正在运行)之后,我现在需要更改在 SurfaceView 的构造函数中创建的对象之一(对象是位图)。这意味着应用程序的 GUI 线程和执行我的 Thread 对象的线程之间的通信。我发现这个页面详细介绍了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()更改位图而绘制位run()图。我可以确定handleMessage()在线程返回run()方法之前将全部完成吗?

4

1 回答 1

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){...}
    }
}
于 2013-12-03T00:08:09.723 回答