当前位置:网站首页>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();
}
}
}
边栏推荐
猜你喜欢
随机推荐
LeetCode刷题
JDBC第一学之进行数据库连接时出现The server time zone.....解决办法
LeetCode_Nov_3rd_Week
file editor
LeetCode_Nov_3rd_Week
调用时序错误导致webrtc无法建立链接
const int * a 与 int * const a 的定义与区别
基于Webrtc和Janus的多人视频会议系统开发6 - 从Janus服务器订阅媒体流
Pipe redirection
LeetCode_22_Apr_2nd_Week
文件编辑器
以太网 ARP
常见的一些排序
抽象类、内部类和接口
【HIT-SC-LAB2】哈工大2022软件构造 实验2
LeetCode_Nov_2nd_Week
结构体传参-C语言
counting cycle
file permission management ugo
[Daily Office][Miscellaneous][vscode]tab space









