要模拟并发只能通过睡眠么?
Topic source创建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...
...
线程多了就乱套了
调用t.start()之后就是并发执行了,
用sleep暂缓一下只是为了让你这个更好看到,并发时程序的执行效果
如果,不使用睡眠 结果感觉 都是正确的
你这说的是个什么玩意,就四条打印语句,怎么就扯上正确错误了?还加锁?共享资源在哪?你往哪加?
- 1
🌙
要模拟并发执行的效果,我们可以在线程中调用Thread.sleep(),强迫当前线程暂停一段时间:
如果,不使用睡眠 结果感觉 都是正确的
是不是不用加锁呢?