开发者

What does lockCanvas mean (elaborate)

I'v been coming to drawing graphics in Android. There's a lot of sample applications out there, but one thing I always seeing is lockCanvas. Can someone explain it clo开发者_Go百科ser since I really don't get it and also because im think it's important to understand to future programming?

An example:

try { 
    c = panel_thread.getHolder().lockCanvas(null);
    synchronized (panel_thread.getHolder()) {
        panel_thread.update();
        panel_thread.onDraw(c);
    }
}

This is what I have for now. How should I interpret this correct? What does synchronized do? Why is it important to assign the canvas-object into a getHolder and lockCanvas?

This part is also confusing:

panel_thread.getHolder().unlockCanvasAndPost(c);

Why is this necessary? I really need a closer explanation. :)


synchronized indicates that only one thread can execute that block of code at a time.

In this example, without the synchronized block, multiple threads could draw graphics at the same time, and the results could be messy. Thus, synchronized ensures that only one thread can draw at a time.

lockCanvas() creates a surface area that you will write to. The reason it's called lockCanvas() is because until you call unlockCanvasAndPost() no other code can call lockCanvas() and write to the surface until your code is finished.

In general, locks are important to understand, specifically when it relates to multithreaded programming. A lock is a synchronization primitive that is used to guard against simultaneous accessing of resources/code by multiple threads. It gets it's name because it behaves much like a physical lock. Generally one thread can obtain a lock, and until it releases the lock, no other thread can obtain the lock. One potential gotcha to using a lock is that misuse of it can lead to a "dead lock" situation, where threads are left waiting for the lock, and it's never released.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜