当前位置:网站首页>多线程顺序输出
多线程顺序输出
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();
}
}
}
边栏推荐
- 浅谈游戏音效测试点
- 【代码学习】
- DRA821 环境搭建
- MNIST手写数字识别 —— ResNet-经典卷积神经网络
- Transformer
- Amazon Cloud Technology Build On-Amazon Neptune's Knowledge Graph-Based Recommendation Model Building Experience
- tensorRT教程——使用tensorRT OP 搭建自己的网络
- 【五一专属】阿里云ECS大测评#五一专属|向所有热爱分享的“技术劳动者”致敬#
- MNIST手写数字识别 —— 基于Mindspore快速构建感知机实现十分类
- 强化学习中,Q-Learning与Sarsa的差别有多大?
猜你喜欢
随机推荐
Code to celebrate the Dragon Boat Festival - Zongzi, your heart
[日常办公][杂项][vscode]tab space
【论文阅读】Exploring Spatial Significance via Hybrid Pyramidal Graph Network for Vehicle Re-identificatio
MNIST Handwritten Digit Recognition - Lenet-5's First Commercial Grade Convolutional Neural Network
Deep Learning Theory - Overfitting, Underfitting, Regularization, Optimizers
LeetCode_Nov_5th_Week
集合--LinkedList
Transformer
[Copy Siege Lion Log] Flying Pulp Academy Intensive Learning 7-Day Punch Camp-Study Notes
Tencent and NetEase have taken action one after another. What is the metaverse that is so popular that it is out of the circle?
MNIST手写数字识别 —— 从零构建感知机实现二分类
Rules.make-适合在编辑模式下看
makefile基础学习
latex-写论文时一些常用设置
fuser 使用—— YOLOV5内存溢出——kill nvidai-smi 无pid 的 GPU 进程
彻底删除MySQL教程
Comparison of oracle's number and postgresql's numeric
代码庆端午--粽你心意
2020-10-29
深度学习,“粮草”先行--浅谈数据集获取之道









