Preventing a thread executing a synchronized method

Enter the following code

    class Test{
       double x;
       public void synchronized a()
       { 
          x = 0;
          //do some more stuff
       }
       public void b() 
       { 
          x = -1; 
       } 
    }

Can a thread in a (), in the middle of a change in x, be superseded by a thread that calls b () on the same object?

Is the method synchronized as a single atomic operation?

I believe that another way is possible (the thread in b () can be replaced by the thread that calls a () on the same object, since b () does not protect my lock on the Test object).

Can someone shed some light on this?

+5
source share
2 answers

synchronizedonly stops other threads from receiving the same monitor. This in no way makes the operation atomic. In particular:

  • ,
  • ,
  • , ,

b() , , a(), b().

+11

b() a() , a(), - b(). , x - x.

, :

class Test{
       double x;
       public void synchronized a()
       { 
          x = 0;
          //do some more stuff
       }
       public void b() 
       { 
          x = -1; 
          a(); //added call to a()
       } 
    }

, Thread 1 [ a() Thread 2 [ b()].

, Thread 1 , Thread 2 a(), JVM ; [ ] . , Thread 2 , Thread 1 a() . Thread 2 [ ] a().

0

All Articles