news 2026/3/21 6:39:07

Java 线程间的通信方式

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
Java 线程间的通信方式

一、概述

在Java中,线程之间的通信主要涉及线程之间如何交换信息或协调行动。常见的线程通信方式有以下几种:

  1. 共享内存(通过共享对象进行通信)
  2. wait/notify机制
  3. Lock和Condition
  4. 使用阻塞队列(BlockingQueue)
  5. 使用管道(PipedInputStream/PipedOutputStream 或 PipedReader/PipedWriter)
  6. 使用信号量(Semaphore)等同步工具
  7. 使用CountDownLatch、CyclicBarrier等同步辅助类
  8. 使用Exchanger
  9. 使用Future和Callable
  10. 使用CompletableFuture

二、详细实现与示例

2.1 共享内存(共享变量)

线程之间通过读写共享的变量来进行通信。这是最常用的一种方式,但需要同步机制来保证数据的一致性(如synchronized、volatile、Lock等)。

// 示例:使用volatile共享变量publicclassSharedVariable{privatevolatilebooleanflag=false;publicvoidsetFlag(){flag=true;}publicvoidwaitForFlag(){while(!flag){// 等待}System.out.println("Flag is true!");}}

2.2 wait()/notify()/notifyAll()机制

这是Object类提供的方法,用于线程间的等待和唤醒。必须搭配synchronized使用,因为wait/notify需要先获得对象的锁。

publicclassWaitNotifyExample{privatefinalObjectlock=newObject();privatebooleancondition=false;// 等待方publicvoidawait()throwsInterruptedException{synchronized(lock){while(!condition){lock.wait();// 释放锁并等待}// 执行后续操作System.out.println("条件满足,继续执行");}}// 通知方publicvoidsignal(){synchronized(lock){condition=true;lock.notify();// 唤醒一个等待线程// lock.notifyAll(); // 唤醒所有等待线程}}}

2.3 Lock和Condition(显式锁)

Lock提供了比synchronized更灵活的锁机制,而Condition则提供了线程间协调等待和唤醒的功能,类似于wait/notify,但可以更精细地控制。

importjava.util.concurrent.locks.*;publicclassLockConditionExample{privatefinalLocklock=newReentrantLock();privatefinalConditioncondition=lock.newCondition();privatebooleanready=false;publicvoidawait()throwsInterruptedException{lock.lock();try{while(!ready){condition.await();// 等待}System.out.println("准备就绪,开始工作");}finally{lock.unlock();}}publicvoidsignal(){lock.lock();try{ready=true;condition.signal();// 发送信号}finally{lock.unlock();}}}

2.4 阻塞队列(BlockingQueue)

BlockingQueue是一个接口,它定义了线程安全的队列,支持阻塞的插入和移除操作。当队列满时,插入操作会被阻塞;当队列空时,移除操作会被阻塞。

importjava.util.concurrent.*;publicclassBlockingQueueExample{privateBlockingQueue<String>queue=newLinkedBlockingQueue<>(10);// 生产者classProducerimplementsRunnable{@Overridepublicvoidrun(){try{Stringitem="item-"+System.currentTimeMillis();queue.put(item);// 队列满时会阻塞System.out.println("生产: "+item);}catch(InterruptedExceptione){Thread.currentThread().interrupt();}}}// 消费者classConsumerimplementsRunnable{@Overridepublicvoidrun(){try{Stringitem=queue.take();// 队列空时会阻塞System.out.println("消费: "+item);}catch(InterruptedExceptione){Thread.currentThread().interrupt();}}}}

2.5 信号量(Semaphore)

信号量用来控制同时访问某个资源的线程数量,也可以用于线程间通信,但更偏向于同步。通过acquire()和release()操作。

importjava.util.concurrent.Semaphore;publicclassSemaphoreExample{privateSemaphoresemaphore=newSemaphore(0);// 初始许可为0publicvoidwaitSignal()throwsInterruptedException{System.out.println("等待信号...");semaphore.acquire();// 获取许可,没有许可时阻塞System.out.println("收到信号,继续执行");}publicvoidsendSignal(){System.out.println("发送信号");semaphore.release();// 释放许可}}

2.6 CountDownLatch

CountDownLatch允许一个或多个线程等待其他线程完成操作;

importjava.util.concurrent.CountDownLatch;publicclassCountDownLatchExample{publicstaticvoidmain(String[]args)throwsInterruptedException{CountDownLatchlatch=newCountDownLatch(3);for(inti=0;i<3;i++){newThread(()->{System.out.println(Thread.currentThread().getName()+" 完成任务");latch.countDown();// 计数器减1}).start();}latch.await();// 等待计数器归零System.out.println("所有任务完成,继续主线程");}}

2.7 CyclicBarrier

CyclicBarrier让一组线程相互等待,到达一个公共屏障点。

importjava.util.concurrent.CyclicBarrier;publicclassCyclicBarrierExample{publicstaticvoidmain(String[]args){CyclicBarrierbarrier=newCyclicBarrier(3,()->{System.out.println("所有线程到达屏障,执行屏障动作");});for(inti=0;i<3;i++){newThread(()->{try{System.out.println(Thread.currentThread().getName()+" 到达屏障");barrier.await();// 等待其他线程System.out.println(Thread.currentThread().getName()+" 继续执行");}catch(Exceptione){e.printStackTrace();}}).start();}}}

2.8 Exchanger

Exchanger用于两个线程之间交换数据。每个线程在exchange()方法处等待,直到两个线程都调用exchange()方法,然后交换数据。

importjava.util.concurrent.Exchanger;publicclassExchangerExample{publicstaticvoidmain(String[]args){Exchanger<String>exchanger=newExchanger<>();newThread(()->{try{Stringdata="Thread1的数据";System.out.println("Thread1发送: "+data);Stringreceived=exchanger.exchange(data);System.out.println("Thread1收到: "+received);}catch(InterruptedExceptione){e.printStackTrace();}}).start();newThread(()->{try{Stringdata="Thread2的数据";System.out.println("Thread2发送: "+data);Stringreceived=exchanger.exchange(data);System.out.println("Thread2收到: "+received);}catch(InterruptedExceptione){e.printStackTrace();}}).start();}}

2.9 管道(Piped Streams)

管道是一种基于流的通信方式,一个线程向管道输出流写数据,另一个线程从管道输入流读数据。这种方式适用于线程间传输数据,但不如阻塞队列常用。

importjava.io.*;publicclassPipedStreamExample{publicstaticvoidmain(String[]args)throwsIOException{PipedOutputStreampos=newPipedOutputStream();PipedInputStreampis=newPipedInputStream(pos);// 写入线程newThread(()->{try{pos.write("Hello from pipe!".getBytes());pos.close();}catch(IOExceptione){e.printStackTrace();}}).start();// 读取线程newThread(()->{try{intdata;while((data=pis.read())!=-1){System.out.print((char)data);}pis.close();}catch(IOExceptione){e.printStackTrace();}}).start();}}

2.10 Future/Callable

通过ExecutorService提交一个Callable任务,返回一个Future对象。主线程可以通过Future.get()方法获取子线程的执行结果,这实际上也是一种线程间通信(获取结果)。

importjava.util.concurrent.*;publicclassFutureExample{publicstaticvoidmain(String[]args)throwsException{ExecutorServiceexecutor=Executors.newSingleThreadExecutor();Callable<String>task=()->{Thread.sleep(1000);return"任务结果";};Future<String>future=executor.submit(task);System.out.println("等待结果...");Stringresult=future.get();// 阻塞等待结果System.out.println("结果: "+result);executor.shutdown();}}

2.11 CompletableFuture(Java 8+)

更强大的异步编程和线程通信。

importjava.util.concurrent.CompletableFuture;publicclassCompletableFutureExample{publicstaticvoidmain(String[]args){// 链式调用和组合CompletableFuture<String>future=CompletableFuture.supplyAsync(()->"Hello").thenApply(s->s+" World").thenApply(String::toUpperCase);future.thenAccept(System.out::println);// 结果: HELLO WORLD}}

三、选择建议

  1. 简单同步:使用synchronized + wait/notify
  2. 复杂同步:使用Lock + Condition
  3. 生产者-消费者:优先选择BlockingQueue
  4. 线程计数/等待:使用CountDownLatch
  5. 线程集合点:使用CyclicBarrier
  6. 数据交换:使用Exchanger
  7. 资源控制:使用Semaphore
  8. 异步结果:使用Future/CompletableFuture

.

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/3/15 11:05:36

快递单据自动录入系统集成GLM-4.6V-Flash-WEB流程

快递单据自动录入系统集成GLM-4.6V-Flash-WEB流程 在物流行业日均处理数亿包裹的今天&#xff0c;一个看似不起眼的环节——快递面单信息录入&#xff0c;正悄然成为效率瓶颈。许多中小物流企业仍依赖人工逐条输入收发地址、电话和物品类型&#xff0c;不仅耗时费力&#xff0…

作者头像 李华
网站建设 2026/3/20 9:03:49

发票识别与信息结构化:GLM-4.6V-Flash-WEB实战案例

发票识别与信息结构化&#xff1a;GLM-4.6V-Flash-WEB实战案例 在企业日常运营中&#xff0c;财务人员每天面对成百上千张发票的手动录入和核对。一张增值税电子普通发票上密密麻麻的文字、各种版式变化、手写备注、甚至扫描模糊或倾斜的图像&#xff0c;都让自动化处理变得异常…

作者头像 李华
网站建设 2026/3/19 16:26:49

Altium Designer多层板布局布线思路深度剖析

Altium Designer多层板布局布线实战精要&#xff1a;从结构设计到信号完整性的系统化思维为什么你的四层板总出问题&#xff1f;一个工程师的“踩坑”自白刚入行那会儿&#xff0c;我接了个项目——给一款工业网关设计核心控制板。主控是STM32H7&#xff0c;带DDR3和千兆以太网…

作者头像 李华
网站建设 2026/3/20 13:05:36

防御性编程实战:别让对方的“宕机”,变成你的“殉情”

防御性编程实战&#xff1a;别让对方的“宕机”&#xff0c;变成你的“殉情” 在软件开发&#xff0c;尤其是涉及数据同步、第三方接口对接的场景中&#xff0c;我们常听到一句话&#xff1a;“永远不要信任外部系统”。 但在实际代码中&#xff0c;很多程序员却写出了最“轻信…

作者头像 李华
网站建设 2026/3/15 14:40:47

GLM-4.6V-Flash-WEB适用于哪些工业级视觉应用场景?

GLM-4.6V-Flash-WEB适用于哪些工业级视觉应用场景&#xff1f; 在智能制造、金融科技和政务服务等领域&#xff0c;AI视觉系统正从“看得见”迈向“看得懂”的关键阶段。传统OCR与目标检测模型虽能提取图像中的文字或框出物体&#xff0c;却难以理解复杂语义——比如判断一张发…

作者头像 李华