search
HomeJavajavaTutorialHow to solve deadlock problem in java

How to solve deadlock problem in java

Nov 28, 2019 pm 04:33 PM
javadeadlock

How to solve deadlock problem in java

一、死锁的定义

死锁是指两个或两个以上的进程在执行过程中,由于竞争资源或者由于彼此通信而造成的一种阻塞的现象,若无外力作用,它们都将无法推进下去。

那么我们换一个更加规范的定义:集合中的每一个进程都在等待只能由本集合中的其他进程才能引发的事件,那么该组进程是死锁的。

免费视频教程推荐:java免费视频教程

二、Java 代码模拟死锁

代码示例:

/**
 * 模拟死锁类
 * */
public class ImitateDeadLock {
	public static void main(String[] args) {
		final Object a=new Object();
		final Object b=new Object();
		//线程 threadA 获取对象 a 的锁之后,休眠10秒, 尝试获取对象 b 的锁
		Thread threadA=new Thread(new Runnable() {
			@Override
			public void run() {
				synchronized (a) {
						System.out.println("threadA 获取到对象 a 的锁");
						try {
							Thread.sleep(10000);
							synchronized (b) {
								System.out.println("threadA 获取到对象 b 的锁");
							}
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						
					
				}
			}
		});
		//线程 threadB 获取对象 b 的锁之后,休眠10秒, 尝试获取对象 a 的锁
		Thread threadB=new Thread(new Runnable() {
			@Override
			public void run() {
				synchronized (b) {
						System.out.println("threadB 获取到对象 b 的锁");
						try {
							Thread.sleep(10000);
							synchronized (a) {
								System.out.println("threadB 获取到对象 a 的锁");
							}
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
				}
			}
		});
		
		threadA.start();
		
		threadB.start();
	}
}

运行结果:

threadA 获取到对象 a 的锁
threadB 获取到对象 b 的锁
无限等待........

三、如何解决

1、确认问题

(1)Jps + Jstack 命令

Jps : 查看当前进程

如下所示, class 名称为 ImitateDeadLock 的进程为我们需要查看的进程。

C:\Users\31415> jps
1256 ImitateDeadLock
9240 Jps
7548 org.eclipse.equinox.launcher_1.3.100.v20150511-1540.jar

jstack : 查看堆栈信息

执行 jstack 命令后,会显示出两个线程互相等待,产生了死锁。

C:\Users\31415>jstack 1256
Java stack information for the threads listed above:
===================================================
"Thread-1":
        at ImitateDeadLock$2.run(ImitateDeadLock.java:37)
        - waiting to lock <0x048b15a8> (a java.lang.Object)
        - locked <0x048b15b0> (a java.lang.Object)
        at java.lang.Thread.run(Thread.java:745)
"Thread-0":
        at ImitateDeadLock$1.run(ImitateDeadLock.java:17)
        - waiting to lock <0x048b15b0> (a java.lang.Object)
        - locked <0x048b15a8> (a java.lang.Object)
        at java.lang.Thread.run(Thread.java:745)

Found 1 deadlock.

2、处理问题

(1)确定的顺序获取锁

例如:我们上面的 Demo 中,两个线程获取锁的顺序都为 先获取对象 a 的锁,在获取对象 b 的锁,就不会出现死锁的问题。

(2)超时放弃

当使用synchronized关键词提供的内置锁时,只要线程没有获得锁,那么就会永远等待下去,然而Lock接口提供了boolean tryLock(long time, TimeUnit unit) throws InterruptedException方法,该方法可以按照固定时长等待锁,因此线程可以在获取锁超时以后,主动释放之前已经获得的所有的锁。通过这种方式,也可以很有效地避免死锁。

想了解更多相关教程请访问:java入门学习

The above is the detailed content of How to solve deadlock problem in java. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor