当前位置:网站首页>多线程顺序输出
多线程顺序输出
2022-08-04 05:31:00 【Louzen】
之前面试被坑过,填坑
public class PrintSorted {
private static final List<MyLock> myLocks = new ArrayList<>();
public static class MyLock {
public String awakeThreadName = "";
public MyLock(String awakeThreadName) {
this.awakeThreadName = awakeThreadName;
}
}
public static void main(String[] args) {
print(10);
synchronized (myLocks.get(0)) {
myLocks.get(0).notifyAll();
}
}
public static void print(int threadNum) {
List<Thread> threads = new ArrayList<>(threadNum);
for (int i = 0; i < threadNum; ++i) {
MyLock myLock = new MyLock("thread-" + i);
myLocks.add(myLock);
}
for (int i = 0; i < threadNum; ++i) {
final int x = i;
threads.add(new Thread() {
@Override
public void run() {
while (true) {
synchronized (myLocks.get(x)) {
try {
myLocks.get(x).wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Thread - " + x);
synchronized (myLocks.get((x + 1) % threadNum)) {
myLocks.get((x + 1) % threadNum).notifyAll();
}
}
}
});
}
for (int i = 0; i < threadNum; ++i) {
threads.get(i).start();
}
}
}
边栏推荐
- 【论文阅读】Mining Cross-Image Semantics for Weakly Supervised Semantic Segmentation
- [English learning][sentence] good sentence
- 光条中心提取方法总结(一)
- 题目1000:输入两个整数a和b,计算a+b的和,此题是多组测试数据
- 【论文阅读】Anchor-Free Person Search
- MNIST手写数字识别 —— 图像分析法实现二分类
- 学习资料re-id
- DeblurGAN-v2: Deblurring (Orders-of-Magnitude) Faster and Better 图像去模糊
- 基于asp.net的法律援助平台的设计与实现(附项目链接)
- tmux概念和使用
猜你喜欢
随机推荐
PostgreSQL schema (Schema)
2020-10-29
PyTorch
AWS uses EC2 to reduce the training cost of DeepRacer: DeepRacer-for-cloud practical operation
度量学习(Metric learning、损失函数、triplet、三元组损失、fastreid)
数据库的简述与常用操作指南
Deep Adversarial Decomposition: A Unified Framework for Separating Superimposed Images
CAS无锁队列的实现
MNIST handwritten digit recognition, sorted by from two to ten
[开发杂项][编辑器][代码阅读]ctags&vim
打金?工作室?账号被封?游戏灰黑产离我们有多近
理想的生活
sbl_init.asm-适合在编辑模式下看
Amazon Cloud Technology Build On 2022 - AIot Season 2 IoT Special Experiment Experience
Copy Siege Lion 5-minute online experience MindIR format model generation
MFC 打开与保存点云PCD文件
MNIST Handwritten Digit Recognition - From Perceptrons to Convolutional Neural Networks
arm-2-基础阶段
Qt日常学习
【论文阅读】Mining Cross-Image Semantics for Weakly Supervised Semantic Segmentation









