Concurency
Two or more threads may have
access to a single object's data.

package com.minte9.threads.lock;
public class ConcurentApp {
public static void main(String[] args) {
ConcurentRunner runner = new ConcurentRunner();
Thread a = new Thread(runner, "Alpha");
Thread b = new Thread(runner, "Beta");
a.start();
b.start();
}
}
class ConcurentRunner implements Runnable {
private int accountBalance = 20;
@Override public void run() {
withdraw(10);
withdraw(10);
}
private void withdraw(int amount) {
System.out.println(
"Account Balance: " + accountBalance
);
if (accountBalance >= amount) {
sleep(500);
accountBalance = accountBalance - amount;
System.out.println(
Thread.currentThread().getName() + " --- withdraw --- 10"
);
}
}
private void sleep(long miliseconds) {
try {
Thread.sleep(miliseconds);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Synchronized
Only
one thread at a time can access the method.

package com.minte9.threads.lock;
public class SynchronizedApp {
public static void main(String[] args) {
SynchronizedRunner runner = new SynchronizedRunner();
Thread a = new Thread(runner, "Alpha");
Thread b = new Thread(runner, "Beta");
a.start();
b.start();
}
}
class SynchronizedRunner implements Runnable {
private int accountBalance = 20;
@Override public void run() {
withdraw(10);
withdraw(10);
}
private synchronized void withdraw(int amount) {
System.out.println(
"Account Balance: " + accountBalance
);
if (accountBalance >= amount) {
sleep(500);
accountBalance = accountBalance - amount;
System.out.println(
Thread.currentThread().getName() + " --- withdraw --- 10"
);
}
}
private void sleep(long miliseconds) {
try {
Thread.sleep(miliseconds);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}