Home > Java > javaTutorial > body text

How to implement inter-thread communication in Java function concurrency and multi-threading?

WBOY
Release: 2024-04-27 12:48:01
Original
1039 people have browsed it

Java Thread communication is crucial in concurrency and multithreading. There are four common methods: shared data, wait-notify mechanism, concurrent queue, and exchange. Sharing data involves using shared variables or objects, wait-notify mechanisms allow threads to wait for specific conditions, concurrent queues provide thread-safe data structures, and exchangers allow paired threads to exchange data when ready.

How to implement inter-thread communication in Java function concurrency and multi-threading?

Java thread communication: communication between threads in concurrency and multi-threading

In concurrent programming in Java, thread communication It is the key to collaboration and resource sharing. There are various mechanisms for passing information between multiple threads and coordinating their behavior. This tutorial will explore common methods of thread communication in Java and illustrate them with practical examples.

1. Sharing data

The simplest way of thread communication is to share public variables or objects between threads. To achieve this, you can use the volatile keyword to ensure visibility and ordering of variables.

// 共享变量
public class SharedData {
    public volatile int value;
}

// 线程 1
public void increment() {
    sharedData.value++;
}

// 线程 2
public void decrement() {
    sharedData.value--;
}
Copy after login

2. Wait-notification mechanism

Use wait() and notify() of Object method, a thread can wait for notification from other threads that a specific condition has been met. This allows threads to sleep before an event occurs, thus avoiding unnecessary CPU usage.

// 生产者-消费者模型
public class WaitNotify {

    private final Queue<Integer> queue;
    private final Object lock = new Object();

    // 生产者线程
    public void produce() {
        synchronized (lock) {
            while (queue.size() >= maxSize) {
                lock.wait();
            }
            queue.add(value);
            lock.notifyAll();
        }
    }

    // 消费者线程
    public void consume() {
        synchronized (lock) {
            while (queue.isEmpty()) {
                lock.wait();
            }
            value = queue.remove();
            lock.notifyAll();
        }
    }
}
Copy after login

3. Concurrent Queue

Java provides concurrent queue classes such as ConcurrentHashMap and ConcurrentLinkedQueue, which can be safely shared among multiple threads. They use an internal locking mechanism to ensure correct operation.

// 使用 ConcurrentLinkedQueue
public class ConcurrencyQueue {

    private final ConcurrentLinkedQueue<Integer> queue = new ConcurrentLinkedQueue<>();

    // 生产者线程
    public void produce() {
        queue.add(value);
    }

    // 消费者线程
    public void consume() {
        Integer value = queue.poll();
    }
}
Copy after login

4. Exchanger

The exchanger allows threads to communicate after pairing. The exchanger releases all threads when they are ready to exchange data.

// 使用 Exchanger
public class ExchangerExample {

    private final Exchanger<Integer> exchanger = new Exchanger<>();

    // 线程 1
    public void exchange() {
        try {
            Integer value = exchanger.exchange(value); // 交换值
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    // 线程 2
    public void exchange() {
        try {
            Integer value = exchanger.exchange(value);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
Copy after login

Through these mechanisms, effective communication between threads can be achieved to build complex high-concurrency applications. Choosing the most appropriate communication method depends on specific application needs and performance considerations.

The above is the detailed content of How to implement inter-thread communication in Java function concurrency and multi-threading?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!