Sunrise
Sunrise

Reputation: 131

Synchronized methods on different objects,different threads

This is my bank class that has deposit and withdraw methods that are synchronized.

public class BankAccount {

private float blance;

public synchronized void deposit(float amount) {
    blance += amount;
}

public synchronized void withdraw(float amount) {
    blance -= amount;
  }
}

Which of this is true:

1: In several object of this class, deposite() method can run with withdraw() method in the same time .

2: In one instance (object) of this class, deposite() method can run with own itself my two threads in the same time.(and consider this for withraw() by itself method).

Is synchronized for prevent running methods in the same time in several objects or in several threads?

Upvotes: 0

Views: 102

Answers (1)

fge
fge

Reputation: 121830

Declaring a non static method as synchronized means the code will be synchronized on the object instance itself. In effet, writing:

public synchronized void doStuff()
{
    whatever();
}

is equivalent to:

public void doStuff()
{
    synchronized(this) {
        whatever();
    }
}

Google for "Java Concurrency in Practice". And buy the book.

Upvotes: 2

Related Questions