当前位置: 首页 > 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();}
}

http://www.dtcms.com/a/272486.html

相关文章:

  • Windows安装DevEco Studio
  • 解决问题:在cmd中能查看到pnpm版本,在vscode终端中却报错
  • [5种方法] 如何将iPhone短信保存到电脑
  • 搜索算法在前端的实践
  • G5打卡——Pix2Pix算法
  • Vue前端导出页面为PDF文件
  • 【HDLBits习题 2】Circuit - Sequential Logic(4)More Circuits
  • AI驱动的业务系统智能化转型:从静态配置到动态认知的范式革命
  • 基础 IO
  • Spring Boot中的中介者模式:终结对象交互的“蜘蛛网”困境
  • JAVA JVM的内存区域划分
  • Redis的常用命令及`SETNX`实现分布式锁、幂等操作
  • Redis Stack扩展功能
  • K8S数据流核心底层逻辑剖析
  • AI进化论06:连接主义的复兴——神经网络的“蛰伏”与“萌动”
  • k8s集群--证书延期
  • 项目进度管控依赖Excel,如何提升数字化能力
  • 调度器与闲逛进程详解,(操作系统OS)
  • UI前端与数字孪生结合案例分享:智慧城市的智慧能源管理系统
  • 数据结构笔记10:排序算法
  • Windows 本地 使用mkcert 配置HTTPS 自签名证书
  • Java并发 - 阻塞队列详解
  • XSS(ctfshow)
  • 文心大模型4.5开源测评:保姆级部署教程+多维度测试验证
  • 图书管理系统(完结版)
  • PyCharm 中 Python 解释器的添加选项及作用
  • 创始人IP如何进阶?三次关键突破实现高效转化
  • QT解析文本框数据——详解
  • pycharm中自动补全方法返回变量
  • 自动化脚本配置网络IP、主机名、网段