Home > Java > javaTutorial > The usage and principle of synchronized keyword in Java parallel programming

The usage and principle of synchronized keyword in Java parallel programming

WBOY
Release: 2024-04-18 13:21:01
Original
1198 people have browsed it

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.

The usage and principle of synchronized keyword in Java parallel programming

The synchronized keyword in Java parallel programming

Principle

synchronizedThe 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.

How to use

synchronized There are two ways to use:

  1. Synchronized method
public synchronized void myMethod() {
    // 同步代码块
}
Copy after login
  1. Synchronized code block
public void myMethod() {
    synchronized (this) {
        // 同步代码块
    }
}
Copy after login

Among them, this represents the current object.

Practical case

The following is a thread-unsafe counter class:

public class UnsafeCounter {
    private int count = 0;

    public void increment() {
        count++;
    }
}
Copy after login

If multiple threads call the increment() method at the same time, it may Resulting in inaccurate count values. To solve this problem, we can synchronize the increment() method using synchronized:

public class SafeCounter {
    private int count = 0;

    public synchronized void increment() {
        count++;
    }
}
Copy after login

Now, multiple threads can safely call increment( ) method because the method is protected by the synchronized 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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template