What makes lockCanvas medium (complicated)

I am going to draw graphics in Android. There are many sample applications, but one thing that I always see is lockCanvas. Can someone explain this closer, because I really do not understand it, and also because it seems important to them to understand the future of programming?

Example:

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

This is what I have now. How should I interpret this correctly? What does synchronization do? Why is it important to assign a canvas object to getHolder and lockCanvas?

This part also confuses:

 panel_thread.getHolder().unlockCanvasAndPost(c); 

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

+5
source share
1 answer

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

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

lockCanvas() creates an area of ​​the surface 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 complete.

In general, locks are important for understanding, especially when it comes to multithreaded programming. Blocking is a synchronization primitive that is used to protect against multiple threads / code accessing simultaneously. He gets this name because he behaves like a physical castle. Typically, one thread can get a lock, and until it releases the lock, no other thread can get a lock. One of the possible ways to use a lock is that improper use of this can lead to a "dead lock" situation, when threads remain waiting for a lock and are never released.

+10
source

Source: https://habr.com/ru/post/888187/


All Articles