一段代码如果在多线程情况下,执行的结果和预期的不符合,就是线程不安全。 为什么说线程是不安全的?话不多说直接上代码。
只有一个main线程时:
public class ThreadUnSafe { private static int globalI = 0; public static void main(String[] args) { for (int i=0;i{ synchronized (lock2){ try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (lock1){ System.out.println("等待资源lock1"); } } }).start(); // main线程持有lock1 等待lock2 synchronized (lock1){ Thread.sleep(500); synchronized (lock2){ System.out.println("等待资源lock2"); } } }查看jvm
"main" Id=1 BLOCKED on java.lang.Object@8778a2e owned by "Thread-2" Id=27 at com.lingyiwin.thread.Dielock.main(Dielock.java:29) - locked java.lang.Object@1c4516b8"Thread-2" Id=27 BLOCKED on java.lang.Object@1c4516b8 owned by "main" Id=1 at com.lingyiwin.thread.Dielock.lambda$main$0(Dielock.java:20) - locked java.lang.Object@8778a2e at com.lingyiwin.thread.Dielock$$Lambda$1/000000000000000000.run(Unknown Source) at java.lang.Thread.run(Thread.java:823) 排查解决1:查看jvm。 jps + jstack 2:定时任务 + jstack 3:结合源代码 4:Object.wait() + Object.notify() / notifyAll() 5:Lock + Condition
避免原则所有的资源都以相同的顺序获取锁; 可能是多个线程分别获取各自的资源,造成死锁。