我正在实现我自己的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()
将完整完成吗?