当前位置:网站首页>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();
}
}
}
边栏推荐
猜你喜欢
随机推荐
Object. RequireNonNull method
抽象类、内部类和接口
[日常办公][ssh]cheatsheet
IP 核之 MMCM/PLL 实验
通过socks5代理下载webrtc源码错误:curl: (7) Can't complete SOCKS5 connection xx.xx.xx.xx
webrtc代码解读二:音视频播放同步过程
IEEE802.X protocol suite
Implementation of CAS lock-free queue
LeetCode_Dec_2nd_Week
JUC锁框架——CountDownLatch、CyclicBarrier和Semaphore
第三章 标准单元库(下)
[Daily office][shell] Common code snippets
webrtc代码解读一:音频数据的接收解码播放过程
【HIT-SC-LAB1】哈工大2022软件构造 实验1
并发概念基础:线程安全与线程间通信
Tensorflow/Pytorch安装(Anaconda环境下,无版本冲突,亲测有效)
Completely remove MySQL tutorial
PS像素画学习-1
使用cef离屏渲染技术实现在线教育课件和webrtc视频回放融合录制
以太网 ARP