多个进程因抢夺系统资源而产生相互等待的现象。
- package com.gui.practise.thread.deadlock;
-
- public class DeadLock {
- private final Object resource1 = new Object();//资源 1
- private final Object resource2 = new Object();//资源 2
- public void leftRight() {
- synchronized (resource1) {
- System.out.println(Thread.currentThread() + "get resource1");
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
-
- System.out.println(Thread.currentThread() + "waiting get resource2");
-
- synchronized (resource2) {
- System.out.println(Thread.currentThread() + "get resource2");
- }
- }
- }
-
- public void rightLeft() {
- synchronized (resource2) {
- System.out.println(Thread.currentThread() + "get resource2");
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
-
- System.out.println(Thread.currentThread() + "waiting get resource1");
-
- synchronized (resource1) {
- System.out.println(Thread.currentThread() + "get resource1");
- }
- }
- }
- }
- package com.gui.practise.thread.deadlock;
-
- public class DeadLockTest {
- public static void main(String[] args) {
- DeadLock dl = new DeadLock();
- new Thread(() -> {
- dl.leftRight();
- }, "线程 1").start();
-
- new Thread(() -> {
- dl.rightLeft();
- }, "线程 2").start();
- }
- }
第一步:jps找到对应进程
第二步:jstack查看对应堆栈信息
下载地址:https://github.com/alibaba/arthas/releases
- package com.gui.practise.thread.deadlock;
-
- public class DeadLock {
- private final Object resource1 = new Object();//资源 1
- private final Object resource2 = new Object();//资源 2
- public void leftRight() {
- synchronized (resource1) {
- System.out.println(Thread.currentThread() + "get resource1");
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
-
- System.out.println(Thread.currentThread() + "waiting get resource2");
-
- synchronized (resource2) {
- System.out.println(Thread.currentThread() + "get resource2");
- }
- }
- }
-
- public void rightLeft() {
- synchronized (resource1) {
- System.out.println(Thread.currentThread() + "get resource1");
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
-
- System.out.println(Thread.currentThread() + "waiting get resource2");
-
- synchronized (resource2) {
- System.out.println(Thread.currentThread() + "get resource2");
- }
- }
- }
- }