The synchronized keyword in Java achieves synchronization by acquiring object locks to prevent data competition caused by multiple threads accessing shared resources at the same time. Its usage includes synchronized methods and synchronized code blocks, where this represents the current object.
synchronized
The keyword is used for synchronized pair sharing Resource access prevents data competition problems caused by multiple threads accessing the same resource at the same time. It achieves synchronization by acquiring a lock (monitor
). When a thread acquires the lock, other threads need to wait until the lock is released before they can continue execution.
Locks are associated with objects. When a thread locks an object, other threads cannot lock the object.
synchronized
There are two ways to use:
public synchronized void myMethod() { // 同步代码块 }
public void myMethod() { synchronized (this) { // 同步代码块 } }
Among them,this
represents the current object.
The following is a thread-unsafe counter class:
public class UnsafeCounter { private int count = 0; public void increment() { count++; } }
If multiple threads call theincrement()
method at the same time, it may Resulting in inaccuratecount
values. To solve this problem, we can synchronize theincrement()
method usingsynchronized
:
public class SafeCounter { private int count = 0; public synchronized void increment() { count++; } }
Now, multiple threads can safely callincrement( )
method because the method is protected by thesynchronized
keyword.
The above is the detailed content of The usage and principle of synchronized keyword in Java parallel programming. For more information, please follow other related articles on the PHP Chinese website!