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

How to achieve thread synchronization using lock mechanism in Java?

WBOY
WBOYOriginal
2023-08-02 13:47:021248browse

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());
    }
}

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());
    }
}

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:
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