当前位置:网站首页>两个线程交互打印奇偶数字
两个线程交互打印奇偶数字
2022-04-23 06:23:00 【cqwoniu】
1、问题描述
用程序实现两个线程交替打印0-100的奇偶数
2、 解题思路
让线程1打印之后唤醒其他线程,然后让出锁,自己进入休眠状态,因为进入了休眠状态就不会与其他线程争抢锁,此时只有线程2能获取锁,线程2以同样的逻辑执行,唤醒线程1并让出持有的锁,自己进入休眠状态。
代码
private int count = 0;
private final Object lock = new Object();
public void turning() throws InterruptedException {
Thread even = new Thread(() -> {
while (count <= 100) {
synchronized (lock) {
System.out.println("偶数: " + count++);
lock.notifyAll();
try {
// 如果还没有结束,则让出当前的锁并休眠
if (count <= 100) {
lock.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
Thread odd = new Thread(() -> {
while (count <= 100) {
synchronized (lock) {
System.out.println("奇数: " + count++);
lock.notifyAll();
try {
// 如果还没有结束,则让出当前的锁并休眠
if (count <= 100) {
lock.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
even.start();
// 确保偶数线程线先获取到锁
Thread.sleep(1);
odd.start();
}
public class TurningRunner implements Runnable {
private int count=0;
private final Object lock = new Object();
@Override
public void run() {
while (count <= 100) {
// 获取锁
synchronized (lock) {
// 拿到锁就打印
System.out.println(Thread.currentThread().getName() + ": " + count++);
// 唤醒其他线程
lock.notifyAll();
try {
if (count <= 100) {
// 如果任务还没有结束,则让出当前的锁并休眠
lock.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
版权声明
本文为[cqwoniu]所创,转载请带上原文链接,感谢
https://blog.csdn.net/cqwoniu/article/details/124330482
边栏推荐
- 华为云MVP邮件
- Solution of wireless intercom system in Commercial Plaza
- ES6之箭头函数细谈
- LATEX公式注意事项
- presto日期函数的使用
- Statement of American photography technology suing Tianmu media for using volcanic engine infringement code
- 南方投资大厦SDC智能通信巡更管理系统
- 枫桥学院开元名庭酒店DMR系统解决方案
- unhandled system error, NCCL version 2.7.8
- quill-editor图片缩放、在一个页面使用多个富文本框、quill-editor上传图片地址为服务器地址
猜你喜欢

PyTorch 10. Learning rate

学习资料

Flexible blind patch of ad hoc network | Beifeng oil and gas field survey solution

DMR system solution of Kaiyuan MINGTING hotel of Fengqiao University

Jupyter Notebook 安装

Emergency air space integrated communication system scheme of Guangxi Power Grid

manjaro安装与配置(vscode,微信,美化,输入法)

Machine vision series (02) -- tensorflow2 3 + win10 + GPU installation

免费开源智能充电桩物联网SAAS云平台

电力行业巡检对讲通信系统
随机推荐
快速下载vscode的方法
嵌入式相关面经(一)
直观理解熵
什么是闭包?
自组网灵活补盲|北峰油气田勘测解决方案
Discussion on the outline of short video technology
海南凤凰机场智能通信解决方案
学习笔记5-梯度爆炸和梯度消失(K折交叉验证)
免费开源充电桩物联网云平台
关于'enum'枚举类型以及结构体的问题。
PyTorch 10. Learning rate
Typora操作技巧说明(一)
SDC intelligent communication patrol management system of Nanfang investment building
go iris框架实现多服务Demo:通过(监听8083端口的)服务1中的接口启动(监听8084端口的)服务2
Solution of self Networking Wireless Communication intercom system in Beifeng oil and gas field
Meishe technology launches professional video editing solution for desktop -- Meiying PC version
How to improve the service efficiency of the hotel without blind spots and long endurance | public and Private Integrated walkie talkie?
南方投资大厦SDC智能通信巡更管理系统
# 可视化常见绘图(二)折线图
HQL语句的调优