Synchronization and locks · Topic 2 of 8
synchronized
Definition​
synchronized lets only one thread at a time run a block of code, using the lock of an object. It protects shared data that several threads change, so updates are not lost.
Example code​
A counter that stays correct with two threads
class Counter {
private int value;
synchronized void increment() { value++; } // only one thread at a time
synchronized int get() { return value; }
}
class Demo {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
Runnable work = () -> { for (int i = 0; i < 100_000; i++) counter.increment(); };
Thread a = new Thread(work), b = new Thread(work);
a.start(); b.start();
a.join(); b.join();
System.out.println(counter.get()); // always 200000; without synchronized it would often be less
}
}
// Output:
// 200000
Finished this page? Track your progress (saved only in your browser).