介绍
本文会持续介绍一些考察非算法的手撕代码,包括但不限于基础思维代码、数据结构代码、算法代码等。
死锁
死锁一直是常在学习计算机编程相关知识时需要特别注意的问题,下面是一个简单的死锁示例代码:
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
| public class DeadLockDemo { private static final Object LOCK_A = new Object(); private static final Object LOCK_B = new Object();
public static void main(String[] args) { new Thread(() -> { synchronized (LOCK_A) { System.out.println(Thread.currentThread().getName() + " 持有锁A,尝试获取锁B"); try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } synchronized (LOCK_B) { System.out.println(Thread.currentThread().getName() + " 获取锁B,执行完成"); } } }, "线程1").start();
new Thread(() -> { synchronized (LOCK_B) { System.out.println(Thread.currentThread().getName() + " 持有锁B,尝试获取锁A"); try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } synchronized (LOCK_A) { System.out.println(Thread.currentThread().getName() + " 获取锁A,执行完成"); } } }, "线程2").start(); } }
|
上述代码最后会输出:
1 2
| 线程1 持有锁A,尝试获取锁B 线程2 持有锁B,尝试获取锁A
|
可以看到,线程1和线程2都在等待对方释放锁,从而导致死锁。