当前位置:网站首页>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();
}
}
}
边栏推荐
猜你喜欢
随机推荐
Unity Day01
【HIT-SC-MEMO7】哈工大2022软件构造 复习笔记7
IEEE802.X protocol suite
IDEA中创建web项目实现步骤
[Daily Office][Miscellaneous][vscode]tab space
【C语言】数组名是什么
LeetCode_Dec_3rd_Week
2022在 Go (Golang) 中使用微服务的系统课程
file editor
counting cycle
安装Apache服务时出现的几个问题, AH00369,AH00526,AH00072....
MySQL存储过程学习笔记(基于8.0)
PS像素画学习-1
【HIT-SC-LAB2】哈工大2022软件构造 实验2
LeetCode_Dec_3rd_Week
webrtc代码解读一:音频数据的接收解码播放过程
结构体传参-C语言
const int * a 与 int * const a 的定义与区别
Object.requireNonNull 方法说明
【HIT-SC-MEMO4】哈工大2022软件构造 复习笔记4