当前位置: 首页 > 图灵资讯 > 技术篇> Java多线程通信方式剖析

Java多线程通信方式剖析

来源:图灵教育
时间:2024-04-12 14:17:51

在 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多线程通信方式分析的详细内容。请关注图灵教育的其他相关文章!