Home Java javaTutorial How to achieve thread synchronization using lock mechanism in Java?

How to achieve thread synchronization using lock mechanism in Java?

Aug 02, 2023 pm 01:47 PM
lock mechanism java programming Thread synchronization

How to use the lock mechanism in Java to achieve thread synchronization?

In multi-threaded programming, thread synchronization is a very important concept. When multiple threads access and modify shared resources at the same time, data inconsistency or race conditions may result. Java provides a locking mechanism to solve these problems and ensure thread-safe access to shared resources.

The locking mechanism in Java is provided by the synchronized keyword and the Lock interface. Next, we'll learn how to use these two mechanisms to achieve thread synchronization.

Example of using the synchronized keyword to implement thread synchronization:

class Counter {
    private int count = 0;

    public synchronized void increment() {
        count++;
    }

    public synchronized int getCount() {
        return count;
    }
}

class IncrementThread extends Thread {
    private Counter counter;

    public IncrementThread(Counter counter) {
        this.counter = counter;
    }

    public void run() {
        for (int i = 0; i < 1000; i++) {
            counter.increment();
        }
    }
}

public class SynchronizedExample {
    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();

        IncrementThread thread1 = new IncrementThread(counter);
        IncrementThread thread2 = new IncrementThread(counter);

        thread1.start();
        thread2.start();

        thread1.join();
        thread2.join();

        System.out.println("Final count: " + counter.getCount());
    }
}
Copy after login

In the above example, the Counter class has a count variable used to represent the value of the counter. The increment() method is modified with the synchronized keyword, which means that only one thread can access and modify the count variable at any time. The getCount() method is also modified with the synchronized keyword to ensure thread safety when obtaining the counter value.

The IncrementThread class is a thread class that accepts a Counter object as a constructor parameter and calls the increment() method in the run() method to increase the value of the counter.

In the main program, we create two IncrementThread threads and pass them to two thread instances respectively. We then start these two threads and wait for them to complete using the join() method. Finally, we print out the final counter value.

Example of using the Lock interface to implement thread synchronization:

class Counter {
    private int count = 0;
    private Lock lock = new ReentrantLock();

    public void increment() {
        lock.lock();
        try {
            count++;
        } finally {
            lock.unlock();
        }
    }

    public int getCount() {
        lock.lock();
        try {
            return count;
        } finally {
            lock.unlock();
        }
    }
}

class IncrementThread extends Thread {
    private Counter counter;

    public IncrementThread(Counter counter) {
        this.counter = counter;
    }

    public void run() {
        for (int i = 0; i < 1000; i++) {
            counter.increment();
        }
    }
}

public class LockExample {
    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();

        IncrementThread thread1 = new IncrementThread(counter);
        IncrementThread thread2 = new IncrementThread(counter);

        thread1.start();
        thread2.start();

        thread1.join();
        thread2.join();

        System.out.println("Final count: " + counter.getCount());
    }
}
Copy after login

In the above example, the Lock interface is used in the increment() and getCount() methods of the Counter class to implement thread synchronization. We create a ReentrantLock instance to acquire and release the lock at the beginning and end of the method respectively.

The code for the IncrementThread class and the main program is the same as in the previous example. Just use the Lock interface instead of the synchronized keyword in the Counter class to achieve thread synchronization.

Summary:

In multi-threaded programming, thread synchronization is an important concept. Java provides the synchronized keyword and Lock interface to achieve thread synchronization. No matter which mechanism is used, it can be guaranteed that only one thread can access and modify shared resources at any time, thereby ensuring thread-safe access.

The above is the sample code for using the lock mechanism in Java to achieve thread synchronization. By understanding and studying these examples, we can better apply thread synchronization to ensure the correctness and performance of multi-threaded programs.

The above is the detailed content of How to achieve thread synchronization using lock mechanism in Java?. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to write a simple student performance report generator using Java? How to write a simple student performance report generator using Java? Nov 03, 2023 pm 02:57 PM

How to write a simple student performance report generator using Java? Student Performance Report Generator is a tool that helps teachers or educators quickly generate student performance reports. This article will introduce how to use Java to write a simple student performance report generator. First, we need to define the student object and student grade object. The student object contains basic information such as the student's name and student number, while the student score object contains information such as the student's subject scores and average grade. The following is the definition of a simple student object: public

How to write a simple student attendance management system using Java? How to write a simple student attendance management system using Java? Nov 02, 2023 pm 03:17 PM

How to write a simple student attendance management system using Java? With the continuous development of technology, school management systems are also constantly updated and upgraded. The student attendance management system is an important part of it. It can help the school track students' attendance and provide data analysis and reports. This article will introduce how to write a simple student attendance management system using Java. 1. Requirements Analysis Before starting to write, we need to determine the functions and requirements of the system. Basic functions include registration and management of student information, recording of student attendance data and

How to deal with thread synchronization and concurrent access issues in C# development How to deal with thread synchronization and concurrent access issues in C# development Oct 08, 2023 pm 12:16 PM

How to deal with thread synchronization and concurrent access issues in C# development requires specific code examples. In C# development, thread synchronization and concurrent access issues are a common challenge. Because multiple threads can access and operate on shared data simultaneously, race conditions and data inconsistencies can arise. To solve these problems, we can use various synchronization mechanisms and concurrency control methods to ensure correct cooperation and data consistency between threads. Mutex lock (Mutex) Mutex lock is the most basic synchronization mechanism used to protect shared resources. Visit when needed

How to deal with thread synchronization and concurrent access issues and solutions in C# development How to deal with thread synchronization and concurrent access issues and solutions in C# development Oct 08, 2023 am 09:55 AM

How to deal with thread synchronization and concurrent access problems and solutions in C# development. With the development of computer systems and processors, the popularity of multi-core processors makes parallel computing and multi-thread programming very important. In C# development, thread synchronization and concurrent access issues are challenges we often face. Failure to handle these issues correctly may lead to serious consequences such as data race (DataRace), deadlock (Deadlock), and resource contention (ResourceContention). Therefore, this article will

ChatGPT Java: How to build an intelligent music recommendation system ChatGPT Java: How to build an intelligent music recommendation system Oct 27, 2023 pm 01:55 PM

ChatGPTJava: How to build an intelligent music recommendation system, specific code examples are needed. Introduction: With the rapid development of the Internet, music has become an indispensable part of people's daily lives. As music platforms continue to emerge, users often face a common problem: how to find music that suits their tastes? In order to solve this problem, the intelligent music recommendation system came into being. This article will introduce how to use ChatGPTJava to build an intelligent music recommendation system and provide specific code examples. No.

Java program: Capitalize first letter of each word in a string Java program: Capitalize first letter of each word in a string Aug 20, 2023 pm 03:45 PM

Astringisaclassof'java.lang'packagethatstoresaseriesofcharacters.ThosecharactersareactuallyString-typeobjects.Wemustenclosethevalueofstringwithindoublequotes.Generally,wecanrepresentcharactersinlowercaseanduppercaseinJava.And,itisalsopossibletoconver

How to use Java to implement the inventory statistics function of the warehouse management system How to use Java to implement the inventory statistics function of the warehouse management system Sep 24, 2023 pm 01:13 PM

How to use Java to implement the inventory statistics function of the warehouse management system. With the development of e-commerce and the increasing importance of warehousing management, the inventory statistics function has become an indispensable part of the warehouse management system. Warehouse management systems written in the Java language can implement inventory statistics functions through concise and efficient code, helping companies better manage warehouse storage and improve operational efficiency. 1. Background introduction Warehouse management system refers to a management method that uses computer technology to perform data management, information processing and decision-making analysis on an enterprise's warehouse. Inventory statistics are

Common performance monitoring and tuning tools in Java development Common performance monitoring and tuning tools in Java development Oct 10, 2023 pm 01:49 PM

Common performance monitoring and tuning tools in Java development require specific code examples Introduction: With the continuous development of Internet technology, Java, as a stable and efficient programming language, is widely used in the development process. However, due to the cross-platform nature of Java and the complexity of the running environment, performance issues have become a factor that cannot be ignored in development. In order to ensure high availability and fast response of Java applications, developers need to monitor and tune performance. This article will introduce some common Java performance monitoring and tuning

See all articles