news 2026/8/10 22:51:42

java生产者-消费者实现方式 线程通信 顺序交替打印

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
java生产者-消费者实现方式 线程通信 顺序交替打印

目录

同步锁实现

juc锁实现

LockSupport 实现

队列实现


看着好多有面试题提到了这个,想到了java里可以用4种方式来实现。

同步锁实现

/** * 生产者-消费者 同步锁实现 */ public class ProducerAndConsumerSynchronized { public static void main(String[] args) throws InterruptedException { final Object object = new Object(); for (int i = 0;i < 5; i++) { Thread producer = new Thread("生产者"+(i+1)){ @Override public void run() { synchronized (object) { try { System.out.println(Thread.currentThread().getName()); object.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } }; Thread consumer = new Thread("消费者"+(i+1)){ @Override public void run() { synchronized (object) { System.out.println(Thread.currentThread().getName()); object.notifyAll(); } } }; producer.start(); consumer.start(); producer.join(); } } }

juc锁实现

上面方式的使用juc中的工具类的实现方式

Lock 相当于 synchronized

Object 的 wait() 相当于 Condition 的 await()

Object 的 notifyAll() 相当于 Condition 的 signalAll()

/** * 生产者-消费者 juc实现 */ public class ProducerAndConsumerLock { public static void main(String[] args) throws InterruptedException { Lock lock = new ReentrantLock(); Condition condition = lock.newCondition(); for (int i = 0;i < 5; i++) { Thread producer = new Thread("生产者"+(i+1)){ @Override public void run() { lock.lock(); try { System.out.println(Thread.currentThread().getName()); condition.await(); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } }; Thread consumer = new Thread("消费者"+(i+1)){ @Override public void run() { lock.lock(); try { System.out.println(Thread.currentThread().getName()); condition.signalAll(); } finally { lock.unlock(); } } }; producer.start(); consumer.start(); producer.join(); } } }

LockSupport 实现

LockSupport 通过 sun.misc.Unsafe 实现线程阻塞和唤醒

/** * 生产者-消费者 juc LockSupport 实现 */ public class ProducerAndConsumerLockSupport { public static void main(String[] args) throws InterruptedException { for (int i = 0;i < 5; i++) { Thread producer = new Thread("生产者"+(i+1)){ @Override public void run() { System.out.println(Thread.currentThread().getName()); LockSupport.park(); } }; Thread consumer = new Thread("消费者"+(i+1)){ @Override public void run() { System.out.println(Thread.currentThread().getName()); LockSupport.unpark(producer); } }; producer.start(); consumer.start(); producer.join(); } } }

队列实现

/** * 生产者-消费者 队列实现 */ public class ProducerAndConsumerQueue { static class Producer implements Runnable { public Producer(BlockingQueue<String> queue) { this.queue = queue; } BlockingQueue<String> queue; @Override public void run() { String name = Thread.currentThread().getName(); try { System.out.println("生产线程 " + name); queue.put(name); } catch (InterruptedException e) { e.printStackTrace(); } } } static class Consumer implements Runnable { public Consumer(BlockingQueue<String> queue) { this.queue = queue; } BlockingQueue<String> queue; @Override public void run() { try { String name = queue.take(); System.out.println("消费线程 " + name); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) { BlockingQueue<String> queue = new LinkedBlockingQueue<>(1); Producer producer = new Producer(queue); Consumer consumer = new Consumer(queue); for (int i = 0; i < 5; i++) { new Thread(producer, "消息" + (i + 1)).start(); new Thread(consumer, "消费者" + (i + 1)).start(); } } }

其中,同步锁、juc锁、LockSupport 也是线程通信。

两个线程交替打印

public class AlternatePrintExample { private static final Object lock = new Object(); private static int count = 1; private static final int MAX = 100; public static void main(String[] args) { Thread oddThread = new Thread(() -> { while (count <= MAX) { synchronized (lock) { if (count % 2 == 1) { System.out.println(Thread.currentThread().getName() + ": " + count); ++count; lock.notify(); } else { try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } }, "奇数"); Thread evenThread = new Thread(() -> { while (count <= MAX) { synchronized (lock) { if (count % 2 == 0) { System.out.println(Thread.currentThread().getName() + ": " + count); ++count; lock.notify(); } else { try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } },"偶数"); oddThread.start(); evenThread.start(); } }
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/8/10 22:44:58

漫画格式转换终极指南:如何用CBconvert轻松解决设备兼容问题

漫画格式转换终极指南&#xff1a;如何用CBconvert轻松解决设备兼容问题 【免费下载链接】cbconvert CBconvert is a Comic Book converter 项目地址: https://gitcode.com/gh_mirrors/cb/cbconvert 还在为不同设备无法读取漫画文件而烦恼吗&#xff1f;您是否遇到过在电…

作者头像 李华
网站建设 2026/8/10 22:42:15

构建企业级Koa应用:中间件选择与架构设计指南

构建企业级Koa应用&#xff1a;中间件选择与架构设计指南 【免费下载链接】koajs-design-note 《Koa.js 设计模式-学习笔记》已完结 &#x1f606; 项目地址: https://gitcode.com/gh_mirrors/ko/koajs-design-note Koa.js作为轻量级Node.js Web框架&#xff0c;以其优雅…

作者头像 李华
网站建设 2026/8/10 22:40:53

5个理由告诉你为什么draw.io桌面版是免费的终极绘图解决方案

5个理由告诉你为什么draw.io桌面版是免费的终极绘图解决方案 【免费下载链接】drawio-desktop Official electron build of draw.io 项目地址: https://gitcode.com/GitHub_Trending/dr/drawio-desktop 还在为昂贵的Visio订阅费用而烦恼吗&#xff1f;想要一款真正免费、…

作者头像 李华
网站建设 2026/8/10 22:40:51

属性系统完全解析:Verdigris中W_PROPERTY的灵活应用

属性系统完全解析&#xff1a;Verdigris中W_PROPERTY的灵活应用 【免费下载链接】verdigris Qt without moc: set of macros to use Qt without needing moc 项目地址: https://gitcode.com/gh_mirrors/ve/verdigris Verdigris作为一款无需moc的Qt开发工具&#xff0c;其…

作者头像 李华
网站建设 2026/8/10 22:37:10

终极指南:如何用OpCore Simplify工具30分钟完成Hackintosh系统配置

终极指南&#xff1a;如何用OpCore Simplify工具30分钟完成Hackintosh系统配置 【免费下载链接】OpCore-Simplify A tool designed to simplify the creation of OpenCore EFI 项目地址: https://gitcode.com/GitHub_Trending/op/OpCore-Simplify 在开源系统定制领域&am…

作者头像 李华