Java 线程间是如何通信的

在 Java 中,线程间通信是通过共享内存或消息传递实现的。以下是详细的线程间通信方式及其示例代码:


1. 共享变量

线程可以通过共享变量进行通信,但需要确保线程安全。常用的方法包括:

  • 使用 volatile 关键字保证可见性。
  • 使用 synchronized 关键字保证同步。

示例代码

class SharedObject {
    private volatile boolean flag = false;

    public void setFlag(boolean flag) {
        this.flag = flag;
    }

    public boolean getFlag() {
        return flag;
    }
}

public class SharedVariableExample {
    public static void main(String[] args) {
        SharedObject shared = new SharedObject();

        Thread writerThread = new Thread(() -> {
            try {
                Thread.sleep(1000); // 模拟耗时操作
                shared.setFlag(true);
                System.out.println("Flag set to true by writer thread.");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        Thread readerThread = new Thread(() -> {
            while (!shared.getFlag()) {
                // 等待 flag 变为 true
            }
            System.out.println("Flag is true, reader thread exiting.");
        });

        writerThread.start();
        readerThread.start();
    }
}

输出:

Flag set to true by writer thread.
Flag is true, reader thread exiting.

2. wait()、notify() 和 notifyAll()

这些方法用于线程间的协调,必须在 synchronized 块或方法中使用。

  • wait():使当前线程等待,释放锁。
  • notify():唤醒一个等待的线程。
  • notifyAll():唤醒所有等待的线程。

示例代码

class SharedResource {
    private boolean ready = false;

    public synchronized void waitForReady() throws InterruptedException {
        while (!ready) {
            wait(); // 等待 ready 变为 true
        }
        System.out.println("Resource is ready, continuing execution.");
    }

    public synchronized void setReady() {
        this.ready = true;
        notifyAll(); // 唤醒所有等待的线程
        System.out.println("Resource is now ready, notifying all waiting threads.");
    }
}

public class WaitNotifyExample {
    public static void main(String[] args) {
        SharedResource shared = new SharedResource();

        Thread waitingThread = new Thread(() -> {
            try {
                shared.waitForReady();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        Thread notifyingThread = new Thread(() -> {
            try {
                Thread.sleep(2000); // 模拟耗时操作
                shared.setReady();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        waitingThread.start();
        notifyingThread.start();
    }
}

输出:

Resource is now ready, notifying all waiting threads.
Resource is ready, continuing execution.

3. BlockingQueue

BlockingQueue 是一个线程安全的队列,支持阻塞操作,常用于生产者-消费者模式。

示例代码

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class ProducerConsumerExample {
    public static void main(String[] args) {
        BlockingQueue<Integer> queue = new LinkedBlockingQueue<>(10);

        // 生产者线程
        Thread producer = new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    queue.put(i); // 将数据放入队列
                    System.out.println("Produced: " + i);
                    Thread.sleep(100); // 模拟生产耗时
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        // 消费者线程
        Thread consumer = new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    int value = queue.take(); // 从队列中取出数据
                    System.out.println("Consumed: " + value);
                    Thread.sleep(200); // 模拟消费耗时
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

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

输出:

Produced: 0
Consumed: 0
Produced: 1
Consumed: 1
Produced: 2
Consumed: 2
...
Produced: 9
Consumed: 9

4. CountDownLatch

CountDownLatch 是一个同步工具,允许一个或多个线程等待其他线程完成操作。

示例代码

import java.util.concurrent.CountDownLatch;

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

        for (int i = 0; i < numThreads; i++) {
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + " is working...");
                try {
                    Thread.sleep(1000); // 模拟工作
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + " finished.");
                latch.countDown(); // 计数器减 1
            }).start();
        }

        latch.await(); // 等待所有线程完成
        System.out.println("All threads have finished.");
    }
}

输出:

Thread-0 is working...
Thread-1 is working...
Thread-2 is working...
Thread-0 finished.
Thread-1 finished.
Thread-2 finished.
All threads have finished.

5. CyclicBarrier

CyclicBarrier 是一个同步工具,允许多个线程在某个屏障点等待,直到所有线程都到达。

示例代码

import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierExample {
    public static void main(String[] args) {
        int numThreads = 3;
        CyclicBarrier barrier = new CyclicBarrier(numThreads, () -> {
            System.out.println("All threads have reached the barrier.");
        });

        for (int i = 0; i < numThreads; i++) {
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + " is working...");
                try {
                    Thread.sleep(1000); // 模拟工作
                    System.out.println(Thread.currentThread().getName() + " reached the barrier.");
                    barrier.await(); // 等待其他线程
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}

输出:

Thread-0 is working...
Thread-1 is working...
Thread-2 is working...
Thread-0 reached the barrier.
Thread-1 reached the barrier.
Thread-2 reached the barrier.
All threads have reached the barrier.

总结

Java 提供了多种线程间通信的方式:

  1. 共享变量:通过 volatilesynchronized 实现。
  2. wait()/notify():用于线程间的协调。
  3. BlockingQueue:用于生产者-消费者模式。
  4. CountDownLatch:等待多个线程完成。
  5. CyclicBarrier:多个线程在屏障点同步。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

冰糖心书房

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值