当前位置:网站首页>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();
}
}
}
边栏推荐
猜你喜欢
随机推荐
Shell基础
基于Webrtc和Janus的多人视频会议系统开发5 - 发布媒体流到Janus服务器
[开发杂项][调试]debug into kernel
SSO单点登陆
20170729
Unity Day01
clssloader与双亲委派
JUC锁框架——基于AQS的实现,从ReentrantLock认识独占和共享
第三章 标准单元库(上)
[English learning][sentence] good sentence
webrtc技术名词和关键技术要点:SVC,REMB,SVC...
线程池原理
罗斯50分
[Daily office][shell] Common code snippets
const int * a 与 int * const a 的定义与区别
【HIT-SC-MEMO4】哈工大2022软件构造 复习笔记4
JUC并发容器——ConcurrentLinkedQueue
JDBC第一学之进行数据库连接时出现The server time zone.....解决办法
strlen 转义字符
vs2017 redist 下载地址