当前位置:网站首页>多线程顺序输出
多线程顺序输出
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();
}
}
}
边栏推荐
猜你喜欢
LeetCode_Nov_4th_Week
Halcon缺陷检测
第一章 绪论
浅谈游戏音效测试点
MNIST手写数字识别 —— Lenet-5首个商用级别卷积神经网络
tensorRT5.15 使用中的注意点
MNIST Handwritten Digit Recognition - Building a Perceptron from Zero for Two-Classification
MNIST Handwritten Digit Recognition - Lenet-5's First Commercial Grade Convolutional Neural Network
深度学习理论——过拟合、欠拟合、正则化、优化器
【论文阅读】Anchor-Free Person Search
随机推荐
Golang环境变量设置(二)--GOMODULE&GOPROXY
多层LSTM
arm-3-中断体系结构
【Copy攻城狮日志】飞浆学院强化学习7日打卡营-学习笔记
投稿相关
tensorRT教程——tensor RT OP理解(实现自定义层,搭建网络)
Pytorch语义分割理解
TypeError: load() missing 1 required positional argument: ‘Loader‘
基于asp.net的法律援助平台的设计与实现(附项目链接)
Pytest common plug-in
target has libraries with conflicting names: libcrypto.a and libssl.a.
光条中心提取方法总结(二)
MOOSE平台使用入门攻略——如何运行官方教程的例子
[日常办公][ssh]cheatsheet
IEEE802.X协议族
[CV-Learning] Linear Classifier (SVM Basics)
光条提取中的连通域筛除
Introduction to Convolutional Neural Networks
[English learning][sentence] good sentence
PP-LiteSeg