Home  >  Article  >  Java  >  Solution to Java multi-thread synchronization exception (ThreadSyncException)

Solution to Java multi-thread synchronization exception (ThreadSyncException)

PHPz
PHPzOriginal
2023-08-18 16:43:501408browse

Solution to Java multi-thread synchronization exception (ThreadSyncException)

Solution to Java multi-thread synchronization exception (ThreadSyncException)

In Java, multi-threading is a common concurrent programming method, but it also brings faced some challenges. One of them is the multi-thread synchronization problem. When multiple threads access shared resources at the same time, data inconsistency or wrong execution order may occur. In order to solve these problems, we need to take some measures to ensure synchronization and sequential execution between threads. This article will introduce some solutions to solve Java multi-thread synchronization exceptions, and attach code examples.

  1. Use the synchronized keyword
    The synchronized keyword is the most basic synchronization mechanism provided by Java and can be used to modify methods and code blocks. When a thread executes synchronized code, other threads need to wait for the thread to complete execution before continuing. This ensures that only one thread can access shared resources at the same time, thereby avoiding data inconsistency problems.

The following is an example of using the synchronized keyword to solve multi-thread synchronization problems:

class Counter {
    private int count = 0;

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

    public void getCount() {
        System.out.println("Count: " + count);
    }
}

class MyThread extends Thread {
    private Counter counter;

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

    public void run() {
        counter.increment();
    }
}

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

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

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

        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        counter.getCount();
    }
}

In the above code, the Counter class represents a counter, and the increment method is modified with the synchronized keyword. Make sure that only one thread can execute this method at a time. The MyThread class represents a thread that increments the counter by calling the counter's increment method. Create two MyThread objects in the Main class and call their start method to start the thread. By using the join method, wait for the two threads to finish executing before printing the counter value.

  1. Using Lock and Condition interfaces
    In addition to the synchronized keyword, Java also provides more flexible Lock and Condition interfaces to solve multi-thread synchronization problems. Compared with the synchronized keyword, the Lock and Condition interfaces provide more fine-grained control and can flexibly control the waiting and waking up of threads.

The following is an example of using the Lock and Condition interfaces to solve multi-thread synchronization problems:

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

class Counter {
    private int count = 0;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

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

    public void getCount() {
        System.out.println("Count: " + count);
    }
}

class MyThread extends Thread {
    private Counter counter;

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

    public void run() {
        counter.increment();
    }
}

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

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

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

        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        counter.getCount();
    }
}

In the above code, the Counter class uses the ReentrantLock and Condition interfaces to implement the counter synchronization control. The increment method first acquires the lock, then increments the counter value, and wakes up the waiting thread through condition.signalAll(). The implementation in MyThread class and Main class is the same as in the above example.

By using the Lock and Condition interfaces, we can more flexibly control the waiting and waking up of threads, thereby providing more fine-grained synchronization control.

Summary:
Java multi-thread synchronization exception is a common problem in concurrent programming, which can be solved by using the synchronized keyword, Lock and Condition interfaces and other means. This article provides code examples of these solutions, hoping to help readers understand synchronization issues in concurrent programming. In actual development, it is crucial to choose an appropriate synchronization mechanism based on specific needs and scenarios.

The above is the detailed content of Solution to Java multi-thread synchronization exception (ThreadSyncException). 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