前言
偶尔发现的小问题
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
|
@Slf4j public class ABC1 {
private static volatile Integer num = 0;
public static void main(String[] args) { Object mutex = new Object();
Thread a = new Thread(() -> { while (true) { log.info("a进入循环"); synchronized (mutex) { log.info("a抢到锁"); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } if (num % 3 == 0) { log.info("a"); num++; }
} } }); Thread b = new Thread(() -> { while (true) { log.info("b进入循环"); synchronized (mutex) { log.info("b抢到锁"); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } if (num % 3 == 1) { log.info("b"); num++; } } } });
Thread c = new Thread(() -> { while (true) { synchronized (mutex) { try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } if (num % 3 == 2) { log.info("c"); num++; } } } }); a.start(); b.start(); c.start(); }
}
|
当时记得一句话,多线程里 sleep 一下能看到很多异常情况哈哈,😂
果然,这里 c 线程就少了两句 log 而已 ,抢到锁的概率大大提高,就有可能出现一两分钟 c 线程一直拿到锁
,不过不sleep的话概率会小很多,刚好从这里可以看出,synchronized 配合 wait 和 notify 的话,这种情况就可以避免了,
减少无用线程的空转