58t.net 58t.net

欢迎光临
我们一直在努力
顶部
域名
云服务器48/月

Java多线程通信方式剖析-java教程-

在 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中文网其它相关文章!

【声明】:本博客不参与任何交易,也非中介,仅记录个人感兴趣的主机测评结果和优惠活动,内容均不作直接、间接、法定、约定的保证。访问本博客请务必遵守有关互联网的相关法律、规定与规则。一旦您访问本博客,即表示您已经知晓并接受了此声明通告。
-六神源码网 -六神源码网