Home >Java >javaTutorial >Analysis of Java multi-threaded communication methods

Analysis of Java multi-threaded communication methods

WBOY
WBOYOriginal
2024-04-12 08:18:01361browse

In Java, multi-thread communication methods include shared variables, wait/notify, semaphores and pipes. Shared variables facilitate data exchange but are prone to concurrency issues; wait/notify uses a synchronization mechanism to wait and wake up between threads; semaphores limit the number of threads accessing resources at the same time; pipes use buffers to transfer data between threads.

Analysis of Java multi-threaded communication methods

Analysis of Java multi-thread communication methods

Introduction

Multi-threading is concurrency An important concept in programming that allows multiple tasks to be performed simultaneously. In order to implement data exchange in a multi-threaded environment, we need to understand various communication methods. This article will take an in-depth look at common multi-threaded communication methods in Java, including shared variables, wait/notify, semaphores, and pipes.

Shared variables

Shared variables are global variables that can be accessed by multiple threads. When one thread modifies a shared variable, other threads can see the changes. However, shared variables are prone to concurrency problems, such as race conditions and unpredictable behavior.

Practical case:

public class SharedVariableExample {
    private static int sharedCounter = 0;

    public static void main(String[] args) throws InterruptedException {
        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                sharedCounter++;
            }
        });

        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                sharedCounter--;
            }
        });

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

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

        System.out.println("最终共享计数器:" + sharedCounter);
    }
}

wait/notify

wait/notify is a built-in synchronization mechanism in Java. The wait() method will put the current thread into a waiting state until other threads call the notify() or notifyAll() method to wake it up.

Practical case:

public class WaitNotifyExample {
    private static Object lock = new Object();

    private static boolean dataAvailable = false;

    public static void main(String[] args) throws InterruptedException {
        Thread producer = new Thread(() -> {
            synchronized (lock) {
                while (!dataAvailable) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                System.out.println("处理数据...");
            }
        });

        Thread consumer = new Thread(() -> {
            synchronized (lock) {
                dataAvailable = true;
                lock.notify();
            }
        });

        producer.start();
        consumer.start();

        producer.join();
        consumer.join();
    }
}

Semaphore

The semaphore is a synchronization mechanism that allows a specific number of threads Access a resource at the same time. When a thread acquires a semaphore, the semaphore counter is decremented; when it releases the semaphore, the counter is incremented.

Practical case:

public class SemaphoreExample {
    private static Semaphore semaphore = new Semaphore(2);

    public static void main(String[] args) throws InterruptedException {
        Thread thread1 = new Thread(() -> {
            try {
                semaphore.acquire();
                System.out.println("线程 1 进入临界区");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                semaphore.release();
            }
        });

        Thread thread2 = new Thread(() -> {
            try {
                semaphore.acquire();
                System.out.println("线程 2 进入临界区");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                semaphore.release();
            }
        });

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

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

Pipeline

Pipeline is a special data structure used for communication between threads. It's like a buffer, one thread can write data and another thread can read data.

Practical case:

public class PipeExample {
    private static PipedOutputStream pos = new PipedOutputStream();
    private static PipedInputStream pis = new PipedInputStream(pos);

    public static void main(String[] args) throws IOException {
        Thread writer = new Thread(() -> {
            try {
                pos.write("你好,世界!".getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                pos.close();
            }
        });

        Thread reader = new Thread(() -> {
            try {
                byte[] data = new byte[1024];
                int length = pis.read(data);
                System.out.println(new String(data, 0, length));
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                pis.close();
            }
        });

        writer.start();
        reader.start();

        writer.join();
        reader.join();
    }
}

The above is the detailed content of Analysis of Java multi-threaded communication methods. 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