Home  >  Article  >  Java  >  How to solve thread contention and contention issues in Java

How to solve thread contention and contention issues in Java

PHPz
PHPzOriginal
2023-10-10 10:25:541255browse

How to solve thread contention and contention issues in Java

How to solve thread contention and contention issues in Java, specific code examples are needed

Thread contention and contention issues are common when developing multi-threaded applications challenges. When multiple threads access and modify shared resources at the same time, data inconsistency or incorrect running results may result. In order to solve these problems, Java provides a variety of mechanisms and tools to synchronize threads and ensure thread safety and correct execution.

1. Use the synchronized keyword to achieve thread synchronization
The synchronized keyword can mark a code block or method as synchronized. Only one thread is allowed to enter the synchronized block or synchronized method at the same time, and other threads will be blocked. . This ensures that shared resources are only accessed by one thread at the same time, avoiding thread competition and contention problems.

The following is a sample code using the synchronized keyword:

public class ThreadDemo implements Runnable{
    private static int count = 0;

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

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

    public static void main(String[] args) throws InterruptedException {
        ThreadDemo threadDemo = new ThreadDemo();
        Thread t1 = new Thread(threadDemo);
        Thread t2 = new Thread(threadDemo);
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(count);
    }
}

In the above code, we use the synchronized keyword to modify the increment() method to ensure that access to the count variable is interactive. repulsive. When two threads access the increment() method at the same time, only one thread can obtain the lock and execute the method, and the other thread will be blocked.

2. Use the Lock interface to achieve thread synchronization
In addition to the synchronized keyword, Java also provides the Lock interface and its implementation class to achieve thread synchronization. Compared with the synchronized keyword, the Lock interface provides more flexible and finer control.

The following is a sample code using the Lock interface:

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadDemo implements Runnable{
    private static int count = 0;
    private static Lock lock = new ReentrantLock();

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

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

    public static void main(String[] args) throws InterruptedException {
        ThreadDemo threadDemo = new ThreadDemo();
        Thread t1 = new Thread(threadDemo);
        Thread t2 = new Thread(threadDemo);
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(count);
    }
}

In the above code, we use the implementation class ReentrantLock of the Lock interface to create a lock object lock. In the increment() method, we first call the lock() method to acquire the lock, and call the unlock() method in the finally block to release the lock. This ensures that the lock is released correctly under any circumstances.

3. Use Atomic classes to achieve thread safety
In addition to using locks to synchronize threads, Java also provides some atomic classes, such as AtomicInteger, AtomicLong, etc., which provide some atomic operations to ensure that threads Safety.

The following is a sample code using the Atomic class:

import java.util.concurrent.atomic.AtomicInteger;

public class ThreadDemo implements Runnable{
    private static AtomicInteger count = new AtomicInteger(0);

    public void increment(){
        count.incrementAndGet();
    }

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

    public static void main(String[] args) throws InterruptedException {
        ThreadDemo threadDemo = new ThreadDemo();
        Thread t1 = new Thread(threadDemo);
        Thread t2 = new Thread(threadDemo);
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(count.get());
    }
}

In the above code, we use the AtomicInteger class to replace the ordinary int type variable, and count by calling the incrementAndGet() method. Auto-increment operation. Because the increment operation of the AtomicInteger class is atomic, it can ensure thread safety.

To sum up, to solve thread competition and contention problems in Java, you can use mechanisms and tools such as the synchronized keyword, Lock interface or Atomic class. Developers can choose appropriate methods based on specific scenarios to ensure thread safety and correct execution.

The above is the detailed content of How to solve thread contention and contention issues 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