当前位置: 首页 > news >正文

多线程交替打印

交替打印ABC



面渣的十二种写法

https://blog.csdn.net/ZHAOJING1234567/article/details/89462442

https://blog.csdn.net/qq_44373419/article/details/139796030

Semaphore

semaphore介绍:https://blog.csdn.net/2501_92540271/article/details/149043567

一般写法

package org.example.printABC;import java.util.concurrent.Semaphore;public class SemaphorePrint {public static final Semaphore ASemaphore = new Semaphore(1);public static final Semaphore BSemaphore = new Semaphore(0);public static final Semaphore CSemaphore = new Semaphore(0);public static void main(String[] args){Thread thread1 = new Thread(new Runnable() {@Overridepublic void run() {for (int i = 0; i < 3; i++) {try {ASemaphore.acquire();System.out.println(Thread.currentThread().getName() +  " 打印A");BSemaphore.release();} catch (InterruptedException e) {throw new RuntimeException(e);}}}}, "thread1");Thread thread2 = new Thread(new Runnable() {@Overridepublic void run() {for (int i = 0; i < 3; i++) {try {BSemaphore.acquire();System.out.println(Thread.currentThread().getName() + " 打印B");CSemaphore.release();} catch (InterruptedException e) {throw new RuntimeException(e);}}}}, "thread2");Thread thread3 = new Thread(new Runnable() {@Overridepublic void run() {for (int i = 0; i < 3; i++) {try {CSemaphore.acquire();System.out.println(Thread.currentThread().getName() + " 打印C");ASemaphore.release();} catch (InterruptedException e){throw new RuntimeException(e);}}}}, "thread3");thread1.start();thread2.start();thread3.start();}
}

更简洁的写法

package org.example.printABC;import java.util.concurrent.Semaphore;public class SemaphorePrintSimple {private final Semaphore semA = new Semaphore(1);private final Semaphore semB = new Semaphore(0);private final Semaphore semC = new Semaphore(0);public static int n = 3;public static void main(String[] args) {SemaphorePrintSimple sem = new SemaphorePrintSimple();new Thread(()->sem.print('A', sem.semA, sem.semB)).start();new Thread(()->sem.print('B', sem.semB, sem.semC)).start();new Thread(()->sem.print('C', sem.semC, sem.semA)).start();}public void print(char ch, Semaphore cur, Semaphore next) {for (int i = 0; i < n; i++) {try {cur.acquire();System.out.println(Thread.currentThread().getName() + ": " + ch);next.release();} catch (InterruptedException e) {throw new RuntimeException(e);}}}
}

ReentrantLock

lock

package org.example.printABC;import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;public class ReentrantLockPrintSimple {private static Lock lock = new ReentrantLock();private static int state = 0;static class MyThread extends Thread {private int n;private int orderNum;private char c;public MyThread(int n, char c, int orderNum) {this.n = n;this.c = c;this.orderNum = orderNum;}@Overridepublic void run() {// 不断轮训for (int i = 0; i < n; ) {// 有资格执行lock.lock();try{// 是否能真正执行if(state % 3 == orderNum){System.out.println(Thread.currentThread().getName() + ": "+ c);i++;state++;}} finally {lock.unlock();}}}}public static void main(String[] args) {new MyThread(3, 'A', 0).start();new MyThread(3, 'B', 1).start();new MyThread(3, 'C', 2).start();}
}
package org.example.printABC;import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;public class ReentrantLockPrint {private static Lock lock = new ReentrantLock();private static int state = 0;public static void main(String[] args) {new Thread(new Runnable() {@Overridepublic void run() {for (int i = 0; i < 10; ) {lock.lock();try {if (state % 3 == 0){System.out.println(Thread.currentThread().getName() + ": A");i++;state ++;}} finally {lock.unlock();}}}}).start();new Thread(new Runnable() {@Overridepublic void run() {for (int i = 0; i < 10; ) {lock.lock();try {if (state % 3 == 1){System.out.println(Thread.currentThread().getName() + ": B");i++;state ++;}} finally {lock.unlock();}}}}).start();new Thread(new Runnable() {@Overridepublic void run() {for (int i = 0; i < 10; ) {lock.lock();try {if (state % 3 == 2){System.out.println(Thread.currentThread().getName() + ": C");i++;state ++;}} finally {lock.unlock();}}}}).start();}
}

lock+condition

package org.example.printABC;import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;public class ReentrantLockConditionPrint {private static int state = 0;private static Lock lock = new ReentrantLock();private static Condition conditionA = lock.newCondition();private static Condition conditionB = lock.newCondition();private static Condition conditionC = lock.newCondition();private void print(char c, int n, int orderNum, Condition cur, Condition next) {for (int i = 0; i < n; ) {lock.lock();try{while (state % 3 != orderNum){cur.await();}System.out.println(Thread.currentThread().getName() + ": " + c);state++;i++;next.signal();} catch (InterruptedException e){throw new RuntimeException(e);} finally {lock.unlock();}}}public static void main(String[] args) {//static方法引用非static方法ReentrantLockConditionPrint rlc = new ReentrantLockConditionPrint();new Thread(()->rlc.print('A',10, 0, conditionA, conditionB)).start();new Thread(()->rlc.print('B',10, 1, conditionB, conditionC)).start();new Thread(()->rlc.print('C',10, 2, conditionC, conditionA)).start();}
}

Sync

package org.example.printABC;public class syncPrint {private static Object lock = new Object();private static int state = 0;public void print(char c,int n, int orderNum){for (int i = 0; i < n; ) {try{synchronized (lock){// 必须是while不能是ifwhile (state % 3 != orderNum){lock.wait();}System.out.println(Thread.currentThread().getName() + ": " + c);state++;i++;// notifyAll要写在syn块内,不要写到finally里lock.notifyAll();}} catch (InterruptedException e) {throw new RuntimeException(e);}}}public static void main(String[] args) {syncPrint syn = new syncPrint();new Thread(()->syn.print('A',10, 0)).start();new Thread(()->syn.print('B',10, 1)).start();new Thread(()->syn.print('C',10, 2)).start();}
}

交替打印0-100

和打印abc区别不大,注意别多打印了

package org.example.printABC;public class syncPrint {private static Object lock = new Object();private static int state = 0;private static volatile int count = 0;public void print(int orderNum){while(count <= 100) {try{synchronized (lock){// 必须是while不能是ifwhile (state % 3 != orderNum){lock.wait();}if(count > 100){//这里不加这个判断条件会打印到102lock.notifyAll();return;}System.out.println(Thread.currentThread().getName() + ": " + count);state++;count++;// notifyAll要写在syn块内,不要写到finally里lock.notifyAll();}} catch (InterruptedException e) {throw new RuntimeException(e);}}}public static void main(String[] args) {syncPrint syn = new syncPrint();new Thread(()->syn.print(0)).start();new Thread(()->syn.print(1)).start();new Thread(()->syn.print(2)).start();}
}

http://www.lryc.cn/news/584578.html

相关文章:

  • 技术学习_检索增强生成(RAG)
  • 【个人笔记】负载均衡
  • 微服务项目远程调用时的负载均衡是如何实现的?
  • Prompt提示词的主要类型和核心原则
  • 【WEB】Polar靶场 Day8 详细笔记
  • Docker 镜像加速站汇总与使用指南
  • SpringBoot系列—MyBatis(xml使用)
  • Flink自定义函数
  • 一个编辑功能所引发的一场知识探索学习之旅(JavaScript、HTML)
  • Android 插件化实现原理详解
  • 虚拟储能与分布式光伏协同优化:新型电力系统的灵活性解决方案
  • Datawhale AI 夏令营:基于带货视频评论的用户洞察挑战赛 Notebook(下篇)
  • Chromium 引擎启用 Skia Graphite后性能飙升
  • 【TGRS 2025】新型:残差Haar离散小波变换下采样,即插即用!
  • 从零构建MVVM框架:深入解析前端数据绑定原理
  • 深入理解 Linux 中的 stat 函数与文件属性操作
  • NGINX系统基于PHP部署应用
  • 开发需要写单元测试吗?
  • Camera2API笔记
  • 记录一下openGauss自启动的设置
  • 《测试开发:从技术角度提升测试效率与质量》
  • io_helper说明
  • 使用Word/Excel管理需求的10个痛点及解决方案Perforce ALM
  • 二层环路避免-STP技术
  • LangChain框架 Prompts、Agents 应用
  • Selenium 4 教程:自动化 WebDriver 管理与 Cookie 提取 || 用于解决chromedriver版本不匹配问题
  • C++实习面试题
  • dexie 前端数据库封装
  • 【前端】jQuery数组合并去重方法总结
  • MinerU2将PDF转成md文件,并分拣图片