java多线程(五)线程间通信

线程间通信是并发编程中的一个重要概念,它允许多个线程之间交换信息或共享数据。

以下是几种常见的线程间通信方式及其示例:

1. 共享内存

共享内存是最基本的线程间通信方式。多个线程可以访问同一块内存区域,通过读写这块内存区域来实现数据交换和信息共享。

示例(Java)

public class SharedMemoryExample {
    private static int sharedCounter = 0;

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

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

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

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

        System.out.println("Final counter value: " + sharedCounter);
    }
}

在这个示例中,两个线程共享一个sharedCounter变量,并通过synchronized块来确保线程安全。

这里加不加synchronized块代码都一样。

2. 消息传递

消息传递是另一种线程间通信方式。线程之间通过发送和接收消息来进行通信。

示例(Java使用wait/notify

public class MessagePassingExample {
    private static final Object lock = new Object();
    private static String message = "";

    public static void main(String[] args) {
        Thread producer = new Thread(() -> {
            synchronized (lock) {
                message = "Hello from Producer";
                lock.notify();
            }
        });

        Thread consumer = new Thread(() -> {
            synchronized (lock) {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Received message: " + message);
            }
        });

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

在这个示例中,生产者线程设置一个消息,并通过notify方法通知消费者线程。消费者线程在wait方法中等待,直到收到通知,然后读取并打印消息。

3. 使用并发工具

Java提供了许多并发工具类,如CountDownLatchCyclicBarrierSemaphore等,这些工具类也可以用于线程间通信。

示例(CountDownLatch

import java.util.concurrent.CountDownLatch;

public class CountDownLatchExample {
    public static void main(String[] args) throws InterruptedException {
        final CountDownLatch latch = new CountDownLatch(2);

        Thread thread1 = new Thread(() -> {
            System.out.println("Thread 1 is running");
            latch.countDown();
        });

        Thread thread2 = new Thread(() -> {
            System.out.println("Thread 2 is running");
            latch.countDown();
        });

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

        latch.await();
        System.out.println("Both threads have finished their execution");
    }
}

在这个示例中,CountDownLatch用于等待两个线程完成它们的执行。每个线程在完成后都会调用countDown方法,当CountDownLatch的计数到达零时,主线程会继续执行并打印消息。

这些示例展示了不同线程间通信方式的基本用法。

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值