synchronized
There are several ways to avoid race conditions, one of them is using syncrhonzied methods or blocks.
synchronized ensures that only one thread can execute it at a time.
syncrhonized blocks
public class Main {
private static int counter = 0;
public static void main(String[] args) {
Object lock = new Object();
for (int i = 0; i < 5; i++) {
Thread thread = new Thread(() -> {
synchronized (lock) {
for (int j = 0; j < 10; j++) {
counter++;
System.out.println(
Thread.currentThread().getName() + " " + counter);
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
thread.start();
}
}
}
syncrhonized methods
This is more effecient than the above example, because only the crucial part is synchronzied and the threads can sleep at the same time.
public class Main {
private static int counter = 0;
public synchronized static void count() {
counter++;
}
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
Thread thread = new Thread(() -> {
for (int j = 0; j < 10; j++) {
count();
System.out.println(
Thread.currentThread().getName() + " " + counter);
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread.start();
}
}
}