Understanding Java synchronized: Code Block Lock, Method Lock, and Thread Safety
This article explains Java's synchronized keyword, demonstrating both synchronized code block locks and method locks with complete code examples, analyzing execution results, and discussing memory-level locking, thread safety, performance drawbacks, and best practices for using synchronized in concurrent programming.
This article introduces the Java synchronized keyword and shows how to use it to protect a shared variable when multiple threads operate on it.
1. Synchronized code block lock – Two threads increment a global counter 10,000 times each. The full implementation is provided below, and the output confirms the final count is 20,000, demonstrating that the synchronized block serializes the execution.
public class SynchronizeCodeBlockLock implements Runnable {
private static SynchronizeCodeBlockLock instance = new SynchronizeCodeBlockLock();
private static int count = 0;
@Override
public void run() {
method();
}
private void method() {
//关键:同步代码块的方式,操作同一变量,达到线程安全的效果
synchronized (this) {
System.out.println("线程名:" + Thread.currentThread().getName() + ",运行开始");
for (int i = 0; i < 10000; i++) {
count++;
}
System.out.println("线程:" + Thread.currentThread().getName() + ",运行结束");
}
}
public static void main(String[] args) {
Thread thread1 = new Thread(instance);
Thread thread2 = new Thread(instance);
thread1.start();
thread2.start();
while (thread1.isAlive() || thread2.isAlive()) {
//若有线程如果还在活动,则不执行下一步(等同于thread.join()方法)
}
System.out.println("期待结果:20000,实际结果:" + count);
}
}Running this code produces:
线程名:Thread-0,运行开始
线程:Thread-0,运行结束
线程名:Thread-1,运行开始
线程:Thread-1,运行结束
期待结果:20000,实际结果:20000The analysis shows that the synchronized keyword forces Thread‑0 to finish before Thread‑1 starts, converting parallel execution into serial execution.
2. Method lock – The same effect is achieved by declaring the entire method as synchronized. The example below demonstrates two threads executing the synchronized method sequentially, each sleeping for 4 seconds to highlight the serialization.
public class MethodLock implements Runnable {
private static MethodLock instance = new MethodLock();
@Override
public void run() {
method();
}
//关键:synchronized可以保证此方法被顺序执行,线程1执行完4秒钟后,线程2再执行4秒。不加synchronized,线程1和线程2将同时执行
private synchronized void method() {
System.out.println("线程:" + Thread.currentThread().getName() + ",运行开始");
try {
//模拟执行一段操作,耗时4秒钟
Thread.sleep(4000);
System.out.println("线程:" + Thread.currentThread().getName() + ",运行结束");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
//模拟:同一个对象下,两个线程,同步执行一个方法(串行执行则为线程安全,并行执行,则为线程不安全,)
Thread thread1 = new Thread(instance);
Thread thread2 = new Thread(instance);
thread1.start();
thread2.start();
while (thread1.isAlive() || thread2.isAlive()) {
}
System.out.println("测试结束");
}
}Output:
线程:Thread-0,运行开始
线程:Thread-0,运行结束
线程:Thread-1,运行开始
线程:Thread-1,运行结束
测试结束Both approaches achieve the same thread‑safety effect.
3. How synchronized ensures thread safety – Every Java object has an intrinsic lock (monitor). When a thread enters a synchronized block or method, it acquires this lock, blocking other threads from entering any synchronized region on the same object until the lock is released. This provides mutual exclusion and memory visibility.
4. Memory‑level behavior – Entering a synchronized block forces the thread to read variables from main memory, and exiting flushes any changes back to main memory, guaranteeing visibility across threads.
5. Drawbacks – Converting parallel execution to serial execution reduces throughput, and the context‑switch overhead caused by thread blocking further degrades performance.
6. Best practices – Do not synchronize on null objects, keep the synchronized scope as small as possible, and avoid deadlocks by careful lock ordering.
7. Summary – Java provides two ways to achieve object‑level locking: synchronized code blocks and synchronized methods. Use the minimal necessary synchronized region to maintain thread safety while preserving performance.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
