当前位置:网站首页>多线程顺序输出
多线程顺序输出
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();
}
}
}
边栏推荐
- 光条中心提取方法总结(二)
- [日常办公][shell]常用代码段
- YOLOV4流程图(方便理解)
- 亚马逊云科技 Build On 2022 - AIot 第二季物联网专场实验心得
- Copy攻城狮5分钟在线体验 MindIR 格式模型生成
- SQL注入详解
- [日常办公][ssh]cheatsheet
- The second official example analysis of the MOOSE platform - about creating a Kernel and solving the convection-diffusion equation
- [CV-Learning] Linear Classifier (SVM Basics)
- Postgresql snapshot
猜你喜欢
Golang环境变量设置(二)--GOMODULE&GOPROXY
Install Minikube Cluster in AWS-EC2
MFC读取点云,只能正常显示第一个,显示后面时报错
arm学习-1-开发板
深度学习理论——过拟合、欠拟合、正则化、优化器
MOOSE平台官方第二个例子分析——关于创建Kernel,求解对流扩散方程
Amazon Cloud Technology Build On 2022 - AIot Season 2 IoT Special Experiment Experience
深度确定性策略梯度(DDPG)
MNIST手写数字识别 —— Lenet-5首个商用级别卷积神经网络
tensorRT教程——tensor RT OP理解(实现自定义层,搭建网络)
随机推荐
基于BiGRU和GAN的数据生成方法
TensorRT 5 初步认识
如何成长为高级工程师?
Tencent and NetEase have taken action one after another. What is the metaverse that is so popular that it is out of the circle?
[开发杂项][编辑器][代码阅读]ctags&vim
双向LSTM
亚马逊云科技 Build On 2022 - AIot 第二季物联网专场实验心得
【论文阅读】Further Non-local and Channel Attention Networks for Vehicle Re-identification
PCL窗口操作
"A minute" Copy siege lion log 】 【 run MindSpore LeNet model
MFC读取点云,只能正常显示第一个,显示后面时报错
集合--LinkedList
深度学习理论 —— 初始化、参数调节
Amazon Cloud Technology Build On-Amazon Neptune's Knowledge Graph-Based Recommendation Model Building Experience
基于asp.net的法律援助平台的设计与实现(附项目链接)
arm-2-基础阶段
Amazon Cloud Technology Build On 2022 - AIot Season 2 IoT Special Experiment Experience
MNIST Handwritten Digit Recognition - Image Analysis Method for Binary Classification
深度确定性策略梯度(DDPG)
counting cycle