博客
关于我
四. 精确通知顺序访问
阅读量:278 次
发布时间:2019-03-01

本文共 3144 字,大约阅读时间需要 10 分钟。

在学习Java多线程编程时,资源共享和多线程安全是非常重要的内容。为了更好地理解,我设计了一个多线程程序,按照顺序启动三个线程AA、BB、CC,它们分别打印5次、10次和15次字符。这个程序需要确保线程之间的资源共享是安全且有序的。

1. 多线程资源共享的实现

为了实现线程间的资源共享,我使用了ReentrantLock和Condition类。ReentrantLock允许同一线程多次获取锁,其他线程需要等待。而Condition则用于线程间的通知和等待,确保线程能够有序地执行任务。

2. 线程操作方法的设计

我为每个线程设计了一个操作方法,分别是print5、print10和print15。每个方法都在获取锁后检查当前的状态,确保线程能够安全地执行任务。

AA线程(print5方法)

  • 打印5次字符,更新状态到2,通知BB线程开始执行。

BB线程(print10方法)

  • 打印10次字符,更新状态到3,通知CC线程开始执行。

CC线程(print15方法)

  • 打印15次字符,更新状态到1,通知AA线程再次执行。

3. 代码实现

import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;class ShareResource {    private int number = 1; // 1:A, 2:B, 3:C    private Lock lock = new ReentrantLock();    private Condition condition1 = lock.newCondition();    private Condition condition2 = lock.newCondition();    private Condition condition3 = lock.newCondition();    public void print5() {        lock.lock();        try {            while (number != 1) {                condition1.await();            }            for (int i = 0; i < 5; i++) {                System.out.println(Thread.currentThread().getName() + "\tA");            }            number = 2;            condition2.signal();        } catch (Exception e) {            e.printStackTrace();        } finally {            lock.unlock();        }    }    public void print10() {        lock.lock();        try {            while (number != 2) {                condition2.await();            }            for (int i = 0; i < 10; i++) {                System.out.println(Thread.currentThread().getName() + "\tB");            }            number = 3;            condition3.signal();        } catch (Exception e) {            e.printStackTrace();        } finally {            lock.unlock();        }    }    public void print15() {        lock.lock();        try {            while (number != 3) {                condition3.await();            }            for (int i = 0; i < 15; i++) {                System.out.println(Thread.currentThread().getName() + "\tC");            }            number = 1;            condition1.signal();        } catch (Exception e) {            e.printStackTrace();        } finally {            lock.unlock();        }    }}public class ThreadOrderAccess {    public static void main(String[] args) {        ShareResource shareResource = new ShareResource();        new Thread(() -> {            for (int i = 0; i < 10; i++) {                shareResource.print5();            }        }, "thread1").start();        new Thread(() -> {            for (int i = 0; i < 10; i++) {                shareResource.print10();            }        }, "thread2").start();        new Thread(() -> {            for (int i = 0; i < 10; i++) {                shareResource.print15();            }        }, "thread3").start();    }}

4. 代码解释

  • 资源共享:使用ReentrantLock和Condition确保线程间的资源共享是安全的。
  • 线程等待与通知:通过while循环确保线程只能在特定状态下获取资源,避免虚假唤醒。
  • 状态管理:通过number变量跟踪当前状态,确保线程按照正确的顺序执行任务。
  • 线程启动:在main方法中启动三个线程,分别执行print5、print10和print15方法。

5. 测试与验证

为了确保程序的正确性,可以运行代码观察输出结果。预期输出应该是:

thread1	A	5次thread2	B	10次thread3	C	15次thread1	A	5次thread2	B	10次thread3	C	15次

通过观察输出,可以确认线程按照预期的顺序执行任务。

转载地址:http://ajco.baihongyu.com/

你可能感兴趣的文章
python3.6.5+cuda9+cudnn7.1+win10+tensorflow-gpu1.9.0下载配置
查看>>
python3.6使用pickle序列化class
查看>>
python3.6入门到高阶(全栈) day027 网络通信协议 osi七层模型
查看>>
Python3.6属性错误:模块‘;异步没有属性‘;运行‘;
查看>>
python3.6版本中的python-weka-wrapper安装失败,错误代码为%1
查看>>
Python3.7安装cv2踩过的坑
查看>>
python写txt文件
查看>>
python关于sorted排序函数详细解析 附实战代码(全)
查看>>
python3.8调用m文件,调用matlab
查看>>
python3.9新特性_Python 3.9 新特性速览
查看>>
Python3.x:遍历select下拉框获取value值
查看>>
python360百科_11月编程排行榜:Python超过Java成第二
查看>>
Python关于Paginator分页函数详细解析 附实战代码
查看>>
python3、ipython3、setup-tools、pip等环境搭建详细总结
查看>>
python3下使用cv2.imwrite存储带有中文路径图片或者绝对路径图片
查看>>
python3与django中@property详解
查看>>
python3中如何表示无穷大
查看>>
Python3中提示:no module named 'wxpy'
查看>>
python3中选择文件对话框的格式打开和保存图片
查看>>
python3为什么print永远都是地址_Python3 print 函数用法总结
查看>>