Discuss / Java / 要模拟并发只能通过睡眠么?

要模拟并发只能通过睡眠么?

Topic source

🌙

#1 Created at ... [Delete] [Delete and Lock User]

要模拟并发执行的效果,我们可以在线程中调用Thread.sleep(),强迫当前线程暂停一段时间:

如果,不使用睡眠 结果感觉 都是正确的

是不是不用加锁呢?

🌙

#2 Created at ... [Delete] [Delete and Lock User]

创建100个线程,问题就出来了....

for (int i = 0; i < 100; i++) {
Thread t2 = new Thread(() -> {
System.out.println("thread start...");
System.out.println("thread end...");
});
t2.start();
}

// t.start();
System.out.println("main end...");

打印结果

...

thread start...

thread start...

thread end...

main end...

thread start...

...

线程多了就乱套了

🌙

#3 Created at ... [Delete] [Delete and Lock User]

一个线程执行一半的时候会被其他线程强行插入

保持热爱

#4 Created at ... [Delete] [Delete and Lock User]

调用t.start()之后就是并发执行了,
用sleep暂缓一下只是为了让你这个更好看到,并发时程序的执行效果

如果,不使用睡眠 结果感觉 都是正确的

你这说的是个什么玩意,就四条打印语句,怎么就扯上正确错误了?还加锁?共享资源在哪?你往哪加?

C

#5 Created at ... [Delete] [Delete and Lock User]
一个线程执行一半的时候会被其他线程强行插入

这就是并发,线程由cpu调度,后续看不明白的可以回头重新看本文

🌙

#6 Created at ... [Delete] [Delete and Lock User]

没有按照我想要的结果打印,就是错误的。

不加sleep,没发模拟出来,当然加锁也不行,这个是cup决定的


  • 1

Reply