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

多线程应用实战

文章目录

  • 1、如何实现多线程交替打印字母和数字,打印效果:A1B2C3D4...
    • Automic
    • BlockingQueue
    • ReentrantLock
    • LockSupport
    • SynchronizedWaitNotify
    • TransferQueueWay
  • 2、实现多个线程顺序打印abc
  • 3、实现阻塞队列

1、如何实现多线程交替打印字母和数字,打印效果:A1B2C3D4…

Automic

public class AutomicWay {volatile static char num1 = 'A';volatile static int num2 = 1;static AtomicInteger atomicInteger = new AtomicInteger(1);public static void main(String[] args) {new Thread(() -> {for (int i = 0; i < 26; i++) {while (atomicInteger.get() != 1) {}System.out.print(num1++);atomicInteger.set(2);}}).start();new Thread(() -> {for (int i = 0; i < 26; i++) {while (atomicInteger.get() != 2) {}System.out.print(num2++);atomicInteger.set(1);}}).start();}
}

BlockingQueue

public class BlockingQueueWay {volatile static char num1 = 'A';volatile static int num2 = 1;public static void main(String[] args) {BlockingQueue queue1 = new ArrayBlockingQueue(1);BlockingQueue queue2 = new ArrayBlockingQueue(1);new Thread(() -> {try {for (int i = 0; i < 26; i++) {System.out.print(num1++);queue2.put("到你");queue1.take();}} catch (InterruptedException e) {e.printStackTrace();}}).start();new Thread(() -> {try {for (int i = 0; i < 26; i++) {queue2.take();System.out.print(num2++);queue1.put("到你");}} catch (InterruptedException e) {e.printStackTrace();}}).start();}
}

ReentrantLock

public class ConditionWay {volatile static char num1 = 'A';volatile static int num2 = 1;public static void main(String[] args) {ReentrantLock lock = new ReentrantLock();Condition conditionA = lock.newCondition();Condition conditionB = lock.newCondition();new Thread(() -> {try {lock.lock();for (int i = 0; i < 26; i++) {System.out.print(num1++);conditionB.signal();conditionA.await();}conditionB.signal();} catch (InterruptedException e) {e.printStackTrace();} finally {lock.unlock();}}).start();new Thread(() -> {try {lock.lock();for (int i = 0; i < 26; i++) {System.out.print(num2++);conditionA.signal();conditionB.await();}conditionA.signal();} catch (InterruptedException e) {e.printStackTrace();} finally {lock.unlock();}}).start();}
}

LockSupport

public class LockSupportWay {static Thread t1,t2 =null;volatile static char num1 = 'A';volatile static int num2 = 1;public static void main(String[] args) {t1 = new Thread(()->{for (int i = 0; i < 26; i++) {System.out.print(num1++);LockSupport.unpark(t2);LockSupport.park(t1);}});t2 = new Thread(()->{for (int i = 0; i < 26; i++) {LockSupport.park(t2);System.out.print(num2++);LockSupport.unpark(t1);}});t1.start();t2.start();}
}

SynchronizedWaitNotify

public class SyncWaitNotifyWay {volatile static char num1 = 'A';volatile static int num2 = 1;public static volatile boolean flag = false;public static void main(String[] args) {Object o = new Object();new Thread(()->{synchronized (o){flag = true;for (int i = 0; i < 26; i++) {System.out.print(num1++);try {o.notify();o.wait();} catch (InterruptedException e) {e.printStackTrace();}}o.notify();}}).start();new Thread(()->{synchronized (o){// 只是为了保证执行A的先跑// while (!flag){// 	try {// 		o.wait();// 	} catch (InterruptedException e) {// 		e.printStackTrace();// 	}// }for (int i = 0; i < 26; i++) {System.out.print(num2++);try {o.notify();o.wait();} catch (InterruptedException e) {e.printStackTrace();}}o.notify();}}).start();}
}

TransferQueueWay

public class TransferQueueWay {volatile static char num1 = 'A';volatile static int num2 = 1;public static void main(String[] args) {TransferQueue transferQueue = new LinkedTransferQueue();new Thread(() -> {try {for (int i = 0; i < 26; i++) {System.out.print(transferQueue.take());transferQueue.transfer(num2++);}} catch (InterruptedException e) {e.printStackTrace();}}).start();new Thread(() -> {try {for (int i = 0; i < 26; i++) {transferQueue.transfer(num1++);System.out.print(transferQueue.take());}} catch (InterruptedException e) {e.printStackTrace();}}).start();}}

2、实现多个线程顺序打印abc

核心代码

public class PrintABC {ReentrantLock lock = new ReentrantLock();Condition conditionA = lock.newCondition();Condition conditionB = lock.newCondition();Condition conditionC = lock.newCondition();private int count;public PrintABC(int count) {this.count = count;}volatile int value = 0;public void printABC() {new Thread(new ThreadA()).start();new Thread(new ThreadB()).start();new Thread(new ThreadC()).start();}class ThreadA implements Runnable {@Overridepublic void run() {lock.lock();try {for (int i = 0; i < count; i++) {while (value % 3 != 0) {conditionA.await();}System.out.print("A");conditionB.signal();value++;}} catch (InterruptedException e) {e.printStackTrace();}}}class ThreadB implements Runnable {@Overridepublic void run() {lock.lock();try {for (int i = 0; i < count; i++) {while (value % 3 != 1) {conditionB.await();}System.out.print("B");conditionC.signal();value++;}} catch (InterruptedException e) {e.printStackTrace();}}}class ThreadC implements Runnable {@Overridepublic void run() {lock.lock();try {for (int i = 0; i < count; i++) {while (value % 3 != 2) {conditionC.await();}System.out.print("C");conditionA.signal();value++;}} catch (InterruptedException e) {e.printStackTrace();}}}
}

测试代码

public static void main(String[] args) {PrintABC printABC = new PrintABC(10);printABC.printABC();
}// 输出结果:ABCABCABCABCABCABCABCABCABCA

3、实现阻塞队列

核心代码

public class ProviderConsumer<T> {private int length;private Queue<T> queue;private ReentrantLock lock = new ReentrantLock();private Condition provideCondition = lock.newCondition();private Condition consumeCondition = lock.newCondition();public ProviderConsumer(int length) {this.length = length;this.queue = new LinkedList<>();}public void provide(T product) {lock.lock();try {while (queue.size() >= length) { // 不能换成if,唤醒后,可能条件已经不满足了provideCondition.await();}queue.add(product);consumeCondition.signal();} catch (InterruptedException e) {e.printStackTrace();} finally {lock.unlock();}}public T consume() {lock.lock();try {while (queue.isEmpty()) { // 不能换成if,唤醒后,可能条件已经不满足了consumeCondition.await();}T product = queue.remove();provideCondition.signal();return product;} catch (InterruptedException e) {e.printStackTrace();} finally {lock.unlock();}return null;}
}

测试代码

public static void main(String[] args) {ProviderConsumer<Integer> providerConsumer = new ProviderConsumer<>(5);new Thread(() -> {for (int i = 0; i < 10; i++) {providerConsumer.provide(1);}}).start();new Thread(() -> {for (int i = 0; i < 10; i++) {providerConsumer.provide(2);}}).start();new Thread(() -> {for (int i = 0; i < 100; i++) {try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(providerConsumer.consume());}}).start();
}
http://www.lryc.cn/news/344493.html

相关文章:

  • selenium解放双手--记某电力学校的刷课脚本
  • JDK 17有可能代替 JDK 8 吗
  • 代码随想录算法训练营第36期DAY23
  • Leetcode 3128. Right Triangles
  • 力扣经典150题第五十三题:基本计算器
  • 如何为 Nestjs 编写单元测试和 E2E 测试
  • 基于Python的LSTM网络实现单特征预测回归任务(TensorFlow)
  • Spring - 8 ( 10000 字 Spring 入门级教程 )
  • 鸿蒙内核源码分析(忍者ninja篇) | 都忍者了能不快吗
  • Linux——守护进程化(独立于用户会话的进程)
  • 安卓开发--按键跳转页面,按键按下变色
  • Ps基础学习笔记
  • spring开发问题总结(持续更新)
  • Android 状态栏WiFi图标的显示逻辑
  • 更改 DeepXDE 的后端
  • SpringBoot之Zuul服务
  • Go-变量
  • 【CTF-Crypto】RSA-选择明密文攻击 一文通
  • Pytorch基础:torch.expand() 和 torch.repeat()
  • 如何正确安装Scrapy 2.6.1并解决常见的Python环境问题
  • 阵痛中的乳业产业,何时才能成为下一个啤酒产业?
  • 关于模型参数融合的思考
  • Windows MySQL本地服务器设置并导入数据库和数据
  • 豪投巨资,澳大利亚在追逐海市蜃楼吗?
  • 面试集中营—Redis架构篇
  • 05_kafka-整合springboot
  • 论UML在学情精准测评系统中的应用
  • Day23 代码随想录打卡|字符串篇---重复的子字符串
  • 【win10 文件夹数量和看到不一致查看隐藏文件已经打开,Thumb文件作妖】
  • ctfshow web入门 sql注入 web224--web233