multithreading - Java synchronized method lock on object, or method? -


If I have 2 synchronized methods in the same class, but each one has access to different variables, 2 Thread can reach those 2 ways at the same time? Does the lock occur on the object, or in the synchronized method is typically found in the form of the variable?

Example:

Class X {Private int A; Private int b Public synchronized ADA () {a ++; } Public synchronized zero (ADB) {b ++; }}

You can use the same example as 2 thread square X to x.addA () and x.addB () At the same time?

If you declare the method as synchonized (as you are typing Public synchronized zero AA () ) you synchronize on the entire object, so the two threads reaching a different variable from this thread will block each other.

If you want to synchronize only one variable at a time, two threads will not block each other while reaching different variables, you can call them synchronized () blocks were a and b object references that you will use:

  public zero addA () {synchronize (a) { A ++; }} Public Zero AddB () {Synchronize (B) {B ++; }}  

But since they are the priorities then you can not do this.

I would suggest you use AtomicInteger instead:

  import java.util.concurrent.atomic.AtomicInteger; Class X {AtomicInteger a; Atomic Integer B; Public ZeroAdA () {acrecrementAndGet (); } Public Zero addB () {b.incrementAndGet (); }}  

Comments

Popular posts from this blog

windows - Heroku throws SQLITE3 Read only exception -

lex - Building a lexical Analyzer in Java -

python - rename keys in a dictionary -