##死锁代码
public class LockSupportThreadTest {
public static void main(String[] args) {
LockSupportThreadTest threadTest = new LockSupportThreadTest();
Thread yym_user_thread2 = new Thread() {
public void run() {
LockSupport.park();
System.out.println("yym_user_thread2");
threadTest.resources(2);
}
};
Thread yym_user_thread1 = new Thread() {
public void run() {
System.out.println("yym_user_thread1");
threadTest.resources(0);
LockSupport.unpark(yym_user_thread2);
}
};
yym_user_thread1.setName("yym_user_thread1");
yym_user_thread1.start();
//
Thread.yield();Thread.yield();Thread.yield();
Thread.yield();Thread.yield();Thread.yield();
yym_user_thread2.setName("yym_user_thread2");
yym_user_thread2.start();
}
public void resources(int number) {
int i = 10/number;
System.out.println("resources"+i);
}
}
##jstack查看死锁原因,yym_user_thread2没有其他线程唤醒
java
"yym_user_thread2" #27 prio=5 os_prio=0 cpu=0.00ms elapsed=96.06s tid=0x0000022b79380000 nid=0x35784 waiting on condition [0x00000070d84ff000]
java.lang.Thread.State: WAITING (parking)
at jdk.internal.misc.Unsafe.park(java.base@11.0.19/Native Method)
at java.util.concurrent.locks.LockSupport.park(java.base@11.0.19/LockSupport.java:323)
at com.newland.mi.thread.LockSupportThreadTest$1.run(LockSupportThreadTest.java:11)
##以上死锁产生原因,还是由于代码书写不规范产生。在finally释放锁
java
try {
threadTest.resources(0);
}finally {
LockSupport.unpark(yym_user_thread2);
}