当前位置:网站首页>Multi-threaded sequential output
Multi-threaded sequential output
2022-08-04 06:43:00 【Louzen】
I was scammed in an interview before,填坑
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();
}
}
}
边栏推荐
猜你喜欢
随机推荐
bind()系统调用的用处
[Development miscellaneous][Debug]debug into kernel
网络通信与Socket编程概述
使用JS在浏览器中打印菱形
gRPC intro 1:RPC
第一章 绪论
彻底删除MySQL教程
结构体传参-C语言
[Development Miscellaneous][Editor][Code Reading]ctags & vim
C语言数组的深度分析
集合---ArrayList的底层
Fabric v1.1 environment construction
Fabric v1.1 环境搭建
【HIT-SC-MEMO2】哈工大2022软件构造 复习笔记2
第二章 STA相关概念
JVM三大常量池与方法区
webrtc代码解读一:音频数据的接收解码播放过程
Treating as key frame since WebRTC-SpsPpsIdrIsH264Keyframe is disabled 解决
MySQL批量修改时间字段
file editor









