首页  >  文章  >  Java  >  Java多线程通信方式剖析

Java多线程通信方式剖析

WBOY
WBOY原创
2024-04-12 08:18:01280浏览

在 Java 中,多线程通信方式包括共享变量、wait/notify、信号量和管道。共享变量方便数据交换但容易出现并发问题;wait/notify 使用同步机制在线程之间等待和唤醒;信号量限制同时访问资源的线程数量;管道使用缓冲区实现线程间的数据传递。

Java多线程通信方式剖析

Java 多线程通信方式剖析

引言

多线程是并发编程中一个重要概念,它允许多个任务同时执行。为了在多线程环境中实现数据交换,我们需要了解各种通信方式。本文将深入探讨 Java 中常用的多线程通信方式,包括共享变量、wait/notify、信号量和管道。

共享变量

共享变量是多个线程可以访问的全局变量。当一个线程修改共享变量时,其他线程可以看到更改。然而,共享变量容易出现并发问题,如竞态条件和不可预知的行为。

实战案例:

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 是 Java 中内置的同步机制。wait() 方法会使当前线程进入等待状态,直到其他线程调用 notify() 或 notifyAll() 方法将其唤醒。

实战案例:

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

信号量

信号量是一种同步机制,它允许特定数量的线程同时访问一个资源。当一个线程获取信号量时,信号量计数器会减少;当它释放信号量时,计数器会增加。

实战案例:

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

管道

管道是一种用于线程之间通信的特殊数据结构。它就像一个缓冲区,一个线程可以写入数据,另一个线程可以读取数据。

实战案例:

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

以上是Java多线程通信方式剖析的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn