lockCanvas and synchronization in Android

2019-09-09 09:54发布

问题:

@Override
   public void run()
   {
     Canvas canvas =  null; // used for drawing               {
     while  (threadIsRunning)
     {
        try
        {
         canvas = surfaceHolder.lockCanvas(null);  // line 1                               

           synchronized(surfaceHolder)             // line 2

                { //do something .....

                }

           }
        }
      }

According to many post and blogs lockCanvas will make a lock on canvas so that multiple access to canvas is not possible and synchronized block is used so that no other thread draw on canvas ..

Ques is if other thread is prevented from having a canvas by lock canvas by forcing it to wait . Then what is need of synchronized block as thread cannot reach this block as it is blocked

回答1:

I think, if lockCanvas cannot obtain lock it will just return null and execution will continue.