Java多线程死锁例子

目录

  • 一、产生死锁的原因
  • 二、如何避免死锁

一、产生死锁的原因

发生死锁的情况: 多个线程需要同时占用多个共享资源而发生需要互相死循环等待的情况,就是,两个线程互相等待着对象释放锁,一直这样僵持下去,所以导致了死锁的产生。

产生死锁代码:

package com.javaagent.thread;public class DieThread implements Runnable {public static Object obj1=new Object();public static Object obj2=new Object();private boolean flag;public DieThread(boolean bl){flag = bl;}@Overridepublic void run() {if(flag) {while(true) {synchronized(obj1) {try {Thread.sleep(1000);}catch (InterruptedException e){e.printStackTrace();}System.out.println("线程" + Thread.currentThread().getName() + "获取obj1锁对象,等待获取obj2锁对象...");synchronized(obj2) {System.out.println(Thread.currentThread().getName() + " ---- obj2.");}}}}else {while(true){synchronized(obj2) {System.out.println("线程" + Thread.currentThread().getName() + "获取obj2锁对象,等待获取obj1锁对象...");synchronized(obj1) {System.out.println(Thread.currentThread().getName() + " ---- obj1.");}}}}}
}
public class Main {public static void main(String[] args){DieThread d1=new DieThread(true);DieThread d2=new DieThread(false);final Thread t1 = new Thread(d1);final Thread t2 = new Thread(d2);t1.setName("DieThread_1");t2.setName("DieThread_2");t1.start();t2.start();}
}

输出结果:

线程DieThread_2获取obj2锁对象,等待获取obj1锁对象...
线程DieThread_1获取obj1锁对象,等待获取obj2锁对象...

采用 visualVM工具 来进行诊断,结果如下图所示:
在这里插入图片描述
从该图中,我们可以看出,Main的 进程ID为84114 ,红框1中提示 检测到死锁 ,然后我们点击红框3来查看 线程Dump 数据,如下图:
在这里插入图片描述
详细信息:

2020-03-04 15:02:44
Full thread dump Java HotSpot(TM) 64-Bit Server VM (25.121-b13 mixed mode):"RMI TCP Connection(idle)" #19 daemon prio=9 os_prio=31 tid=0x00007ff1db108800 nid=0x5f03 waiting on condition [0x0000700001961000]java.lang.Thread.State: TIMED_WAITING (parking)at sun.misc.Unsafe.park(Native Method)- parking to wait for  <0x0000000796082e28> (a java.util.concurrent.SynchronousQueue$TransferStack)at java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:215)at java.util.concurrent.SynchronousQueue$TransferStack.awaitFulfill(SynchronousQueue.java:460)at java.util.concurrent.SynchronousQueue$TransferStack.transfer(SynchronousQueue.java:362)at java.util.concurrent.SynchronousQueue.poll(SynchronousQueue.java:941)at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1066)at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1127)at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)at java.lang.Thread.run(Thread.java:745)Locked ownable synchronizers:- None"JMX server connection timeout 18" #18 daemon prio=9 os_prio=31 tid=0x00007ff1da87c800 nid=0x5d03 in Object.wait() [0x000070000185e000]java.lang.Thread.State: TIMED_WAITING (on object monitor)at java.lang.Object.wait(Native Method)at com.sun.jmx.remote.internal.ServerCommunicatorAdmin$Timeout.run(ServerCommunicatorAdmin.java:168)- locked <0x00000007964a9dc8> (a [I)at java.lang.Thread.run(Thread.java:745)Locked ownable synchronizers:- None"RMI Scheduler(0)" #17 daemon prio=9 os_prio=31 tid=0x00007ff1da895800 nid=0x5b03 waiting on condition [0x000070000175b000]java.lang.Thread.State: TIMED_WAITING (parking)at sun.misc.Unsafe.park(Native Method)- parking to wait for  <0x00000007960ab5d8> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)at java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:215)at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.awaitNanos(AbstractQueuedSynchronizer.java:2078)at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:1093)at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:809)at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1067)at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1127)at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)at java.lang.Thread.run(Thread.java:745)Locked ownable synchronizers:- None"RMI TCP Connection(1)-10.0.5.39" #16 daemon prio=9 os_prio=31 tid=0x00007ff1d99ed800 nid=0x5903 runnable [0x0000700001657000]java.lang.Thread.State: RUNNABLEat java.net.SocketInputStream.socketRead0(Native Method)at java.net.SocketInputStream.socketRead(SocketInputStream.java:116)at java.net.SocketInputStream.read(SocketInputStream.java:171)at java.net.SocketInputStream.read(SocketInputStream.java:141)at java.io.BufferedInputStream.fill(BufferedInputStream.java:246)at java.io.BufferedInputStream.read(BufferedInputStream.java:265)- locked <0x00000007963eced8> (a java.io.BufferedInputStream)at java.io.FilterInputStream.read(FilterInputStream.java:83)at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:550)at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:683)at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler$$Lambda$3/657644190.run(Unknown Source)at java.security.AccessController.doPrivileged(Native Method)at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)at java.lang.Thread.run(Thread.java:745)Locked ownable synchronizers:- <0x0000000796299c10> (a java.util.concurrent.ThreadPoolExecutor$Worker)"RMI TCP Accept-0" #15 daemon prio=9 os_prio=31 tid=0x00007ff1d9941800 nid=0x570f runnable [0x0000700001555000]java.lang.Thread.State: RUNNABLEat java.net.PlainSocketImpl.socketAccept(Native Method)at java.net.AbstractPlainSocketImpl.accept(AbstractPlainSocketImpl.java:409)at java.net.ServerSocket.implAccept(ServerSocket.java:545)at java.net.ServerSocket.accept(ServerSocket.java:513)at sun.management.jmxremote.LocalRMIServerSocketFactory$1.accept(LocalRMIServerSocketFactory.java:52)at sun.rmi.transport.tcp.TCPTransport$AcceptLoop.executeAcceptLoop(TCPTransport.java:400)at sun.rmi.transport.tcp.TCPTransport$AcceptLoop.run(TCPTransport.java:372)at java.lang.Thread.run(Thread.java:745)Locked ownable synchronizers:- None"Attach Listener" #13 daemon prio=9 os_prio=31 tid=0x00007ff1db028800 nid=0x5303 waiting on condition [0x0000000000000000]java.lang.Thread.State: RUNNABLELocked ownable synchronizers:- None"DestroyJavaVM" #12 prio=5 os_prio=31 tid=0x00007ff1da1ac000 nid=0x1403 waiting on condition [0x0000000000000000]java.lang.Thread.State: RUNNABLELocked ownable synchronizers:- None"DieThread_2" #11 prio=5 os_prio=31 tid=0x00007ff1d9839800 nid=0x5103 waiting for monitor entry [0x000070000134f000]java.lang.Thread.State: BLOCKED (on object monitor)at com.javaagent.thread.DieThread.run(DieThread.java:37)- waiting to lock <0x000000079585bee0> (a java.lang.Object)- locked <0x000000079585bef0> (a java.lang.Object)at java.lang.Thread.run(Thread.java:745)Locked ownable synchronizers:- None"DieThread_1" #10 prio=5 os_prio=31 tid=0x00007ff1d9835800 nid=0x4f03 waiting for monitor entry [0x000070000124c000]java.lang.Thread.State: BLOCKED (on object monitor)at com.javaagent.thread.DieThread.run(DieThread.java:26)- waiting to lock <0x000000079585bef0> (a java.lang.Object)- locked <0x000000079585bee0> (a java.lang.Object)at java.lang.Thread.run(Thread.java:745)Locked ownable synchronizers:- None"Service Thread" #9 daemon prio=9 os_prio=31 tid=0x00007ff1d9835000 nid=0x4b03 runnable [0x0000000000000000]java.lang.Thread.State: RUNNABLELocked ownable synchronizers:- None"C1 CompilerThread2" #8 daemon prio=9 os_prio=31 tid=0x00007ff1da87f800 nid=0x4903 waiting on condition [0x0000000000000000]java.lang.Thread.State: RUNNABLELocked ownable synchronizers:- None"C2 CompilerThread1" #7 daemon prio=9 os_prio=31 tid=0x00007ff1d98c5800 nid=0x4703 waiting on condition [0x0000000000000000]java.lang.Thread.State: RUNNABLELocked ownable synchronizers:- None"C2 CompilerThread0" #6 daemon prio=9 os_prio=31 tid=0x00007ff1da886000 nid=0x4503 waiting on condition [0x0000000000000000]java.lang.Thread.State: RUNNABLELocked ownable synchronizers:- None"Monitor Ctrl-Break" #5 daemon prio=5 os_prio=31 tid=0x00007ff1da884800 nid=0x4303 runnable [0x0000700000c3a000]java.lang.Thread.State: RUNNABLEat java.net.SocketInputStream.socketRead0(Native Method)at java.net.SocketInputStream.socketRead(SocketInputStream.java:116)at java.net.SocketInputStream.read(SocketInputStream.java:171)at java.net.SocketInputStream.read(SocketInputStream.java:141)at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)- locked <0x00000007958fc840> (a java.io.InputStreamReader)at java.io.InputStreamReader.read(InputStreamReader.java:184)at java.io.BufferedReader.fill(BufferedReader.java:161)at java.io.BufferedReader.readLine(BufferedReader.java:324)- locked <0x00000007958fc840> (a java.io.InputStreamReader)at java.io.BufferedReader.readLine(BufferedReader.java:389)at com.intellij.rt.execution.application.AppMainV2$1.run(AppMainV2.java:64)Locked ownable synchronizers:- None"Signal Dispatcher" #4 daemon prio=9 os_prio=31 tid=0x00007ff1db029800 nid=0x360f runnable [0x0000000000000000]java.lang.Thread.State: RUNNABLELocked ownable synchronizers:- None"Finalizer" #3 daemon prio=8 os_prio=31 tid=0x00007ff1d9820800 nid=0x3003 in Object.wait() [0x000070000092e000]java.lang.Thread.State: WAITING (on object monitor)at java.lang.Object.wait(Native Method)- waiting on <0x0000000795588ec8> (a java.lang.ref.ReferenceQueue$Lock)at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:143)- locked <0x0000000795588ec8> (a java.lang.ref.ReferenceQueue$Lock)at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:164)at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:209)Locked ownable synchronizers:- None"Reference Handler" #2 daemon prio=10 os_prio=31 tid=0x00007ff1d9810800 nid=0x2e03 in Object.wait() [0x000070000082b000]java.lang.Thread.State: WAITING (on object monitor)at java.lang.Object.wait(Native Method)- waiting on <0x0000000795586b68> (a java.lang.ref.Reference$Lock)at java.lang.Object.wait(Object.java:502)at java.lang.ref.Reference.tryHandlePending(Reference.java:191)- locked <0x0000000795586b68> (a java.lang.ref.Reference$Lock)at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:153)Locked ownable synchronizers:- None"VM Thread" os_prio=31 tid=0x00007ff1da026800 nid=0x2c03 runnable "GC task thread#0 (ParallelGC)" os_prio=31 tid=0x00007ff1d9810000 nid=0x2403 runnable "GC task thread#1 (ParallelGC)" os_prio=31 tid=0x00007ff1da00d000 nid=0x2603 runnable "GC task thread#2 (ParallelGC)" os_prio=31 tid=0x00007ff1da00d800 nid=0x2803 runnable "GC task thread#3 (ParallelGC)" os_prio=31 tid=0x00007ff1da00e000 nid=0x2a03 runnable "VM Periodic Task Thread" os_prio=31 tid=0x00007ff1da80d000 nid=0x4d03 waiting on condition JNI global references: 354Found one Java-level deadlock:
=============================
"DieThread_2":waiting to lock monitor 0x00007ff1da80ad58 (object 0x000000079585bee0, a java.lang.Object),which is held by "DieThread_1"
"DieThread_1":waiting to lock monitor 0x00007ff1da808418 (object 0x000000079585bef0, a java.lang.Object),which is held by "DieThread_2"Java stack information for the threads listed above:
===================================================
"DieThread_2":at com.javaagent.thread.DieThread.run(DieThread.java:37)- waiting to lock <0x000000079585bee0> (a java.lang.Object)- locked <0x000000079585bef0> (a java.lang.Object)at java.lang.Thread.run(Thread.java:745)
"DieThread_1":at com.javaagent.thread.DieThread.run(DieThread.java:26)- waiting to lock <0x000000079585bef0> (a java.lang.Object)- locked <0x000000079585bee0> (a java.lang.Object)at java.lang.Thread.run(Thread.java:745)Found 1 deadlock.

通过上面的线程Dump文件信息,我们可以看出来发生了死锁,下面也列出了java级别的锁问题和栈信息:

Found one Java-level deadlock:
=============================
"DieThread_2":waiting to lock monitor 0x00007ff1da80ad58 (object 0x000000079585bee0, a java.lang.Object),which is held by "DieThread_1"
"DieThread_1":waiting to lock monitor 0x00007ff1da808418 (object 0x000000079585bef0, a java.lang.Object),which is held by "DieThread_2"Java stack information for the threads listed above:
===================================================
"DieThread_2":at com.javaagent.thread.DieThread.run(DieThread.java:37)- waiting to lock <0x000000079585bee0> (a java.lang.Object)- locked <0x000000079585bef0> (a java.lang.Object)at java.lang.Thread.run(Thread.java:745)
"DieThread_1":at com.javaagent.thread.DieThread.run(DieThread.java:26)- waiting to lock <0x000000079585bef0> (a java.lang.Object)- locked <0x000000079585bee0> (a java.lang.Object)at java.lang.Thread.run(Thread.java:745)Found 1 deadlock.

并且栈信息中,可以定位到死锁发生的地方。

如果解决死锁,那是因为代码的逻辑存在问题,可以调整代码的逻辑或者业务,来避免死锁。

二、如何避免死锁

  • 避免一个线程同时获取多个锁

  • 避免一个线程在锁内同时占用多个资源,尽量保证每个锁只占用一个资源

  • 尝试使用定时锁,使用 lock.tryLock(timeout) 来替代使用内部锁机制。

  • 对于数据库锁,加锁和解锁必须在一个数据库连接里,否则会出现解锁失败的情况。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/446864.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

安卓四大组件简介

安卓四大组件 Activity活动&#xff0c;Service服务&#xff0c;BroadcastRecevicer广播接受器&#xff0c;Content Provider内容提供者 Activity活动 所有程序的流程都运行在activity中 Service服务 只能后台运行&#xff0c;没有界面的长生命周期的代码 BroadcastRece…

WebLogic域的创建与发布

目录一、前言二、准备三、创建域步骤第一步&#xff1a;直接【回车】第二步&#xff1a;直接【回车】第三步&#xff1a;直接【回车】第四步&#xff1a;输入域名称后【回车】第五步&#xff1a;直接【回车】第六步&#xff1a;直接【回车】&#xff08;此步骤是提示域的存放目…

WebLogic启动失败:java.lang.AssertionError: Could not obtain the localhost address.

目录一、错误信息二、解决方案第一步&#xff1a;查看本机计算机名称第二步&#xff1a;编辑hosts文件一、错误信息 linux下启动WebLogic报如下错误&#xff1a; 二、解决方案 此错误多半是hosts文件不对导致的。 解决步骤如下&#xff1a; 第一步&#xff1a;查看本机计…

Windows查找JDK的路径

第一步&#xff1a;确定是否安装JDK 在控制台输入&#xff1a; java -version输出结果&#xff1a; 此时说明你电脑安装了JDK。 第二步&#xff1a;查找路径 然后在控制台输入&#xff1a; java -verbose输出结果&#xff1a; 从最后的jre目录可以找到相应的jdk目录。 …

安卓布局中xml文件属性和ID简介

编写xml属性 加载xml资源 当编译应用时&#xff0c;系统会将每个xml文件编译为view资源 属性 xml属性&#xff1a;特有属性&#xff0c;共有属性&#xff0c;其他属性&#xff08;布局参数&#xff09; ID ——在结构树中对view对象唯一标识 编译应用后&#xff0c;系统以…

Java监控工具VisualVM

目录一、简介二、内存分析1、Heap堆三、CPU分析四、线程分析一、简介 VisualVM 是一款免费的&#xff0c;集成了多个JDK命令行工具的可视化工具&#xff0c;它能为您提供强大的分析能力&#xff0c;对Java应用程序做 性能分析和调优 。这些功能包括 生成和分析海量数据、跟踪内…

C++数据类型

C 数据类型 |–基本数据类型: 整型 short短整型 2 int基本整型4 long长整型 8 浮点型 float单精度型 4 double双精度型 8 long double长双精度型 16 字符型 char 1 逻辑型 bool 1 空类型 void |–构造类型 数组类型 构造体类型 struct 共用体类型 union 枚举类型 enum 类类型…

Android Gradle 多渠道打包、动态配置AppName

目录一、简介二、Gradle多渠道打包1、普通做法2、Gradle多渠道打包一、简介 因为国内Android应用分发市场的现状&#xff0c;我们在发布APP时&#xff0c;一般需要生成多个渠道包&#xff0c;上传到不同的应用市场。这些渠道包需要包含不同的渠道信息&#xff0c;在APP和后台交…

Android Gradle 批量修改生成的apk文件名

目录一、简介二、代码实现1、 Gradle 3.0以下版本2、Gradle 3.0以上版本一、简介 平时开发都知道&#xff0c;我们要上线的时候需要在Android studio打包apk文件&#xff0c;可是默认的打包名是app-release.apk或者app-debug.apk这样的名字&#xff0c;太没有辨识度了。 下面…

Android Studio 代理设置以及代理完全清除

目录一、代理设置二、代理完全清除一、代理设置 首先我们来看下怎样设置代理&#xff0c;Mac下打开【Preferences…】&#xff0c;然后搜索"HTTP"&#xff0c;选择【HTTP Proxy】&#xff0c;按图中设置配置好后&#xff0c;点击【Apply】&#xff0c;然后在点击【O…

安卓布局位置,dp与px的区别

手机6寸—指对角线 布局位置 横轴—x轴 纵轴—y轴 一个像素点 dp与Px dp:设备无关像素,与像素密度相关,像素距离 dpi:像素密度,每英寸包含的像素数 px:屏幕上一个物理像素点 ldpi低密度 1dp0.75px mdpi中密度 1dp1px hdpi高密度 1dp1.5px xhdpi超高密度 1dp2px xxhdpi超…

Android程序结构

Project方式 .gradle文件夹:编译相关生成 .idea文件夹:idea生成 app文件夹----应用程序的源代码和资源 build----编译后的文件存放的位置,最终apk文件存放的位置 libs:存放.jar和.so文件 src:AndroidTest与test存放测试相关的内容 main中Java文件夹存放Java源码,res文件…

通过Github创建Android库供其他项目依赖引用

目录一、简介二、实现第一步&#xff1a;将自己的项目托管到Github上。第二步&#xff1a;点击releases。第三步&#xff1a;创建release。第四步&#xff1a;填写版本号、名称、描述信息。第五步&#xff1a;点击【Publish release】。第六步&#xff1a;复制项目路径。第七步…

使用boost模板函数实现读写锁

介绍 shared_mutex即读写锁&#xff0c;不同与我们常用的独占式锁mutex&#xff0c;shared_mutex是共享与独占共存的锁&#xff0c;实现了读写锁的机制&#xff0c;即多个读线程一个写线程&#xff0c;通常用于对于一个共享区域的读操作比较频繁&#xff0c;而写操作比较少的情…

安卓内边距padding与外边距magrin

内边距padding与外边距margin 内边距只有容器才有,即里面要有视图 具体示例

Android Studio发布项目到jcenter

目录一、创建Bintray账户及Maven仓库二、上传项目到jcenter1、配置Android项目2、Gradle命令上传3、在项目中引用4、Add to JCenter三、Demo示例一、创建Bintray账户及Maven仓库 1、打开Bintray首页&#xff0c;点击 For an Open Source Account &#xff0c;快速注册或者用第…

Android MotionEvent中getX()、getRawX()和getTop()的区别

为了展示getX()、getRawX()和getTop()方法的区别&#xff0c;我们写了一个简单的测试Demo&#xff0c;我们写了一个自定义控件&#xff08;继承ImageView&#xff09;。 package com.demo.ui;import android.content.Context; import android.support.annotation.Nullable; im…

毛概 第二章新民主主义革命理论

1.新民主主义革命的总路线 2.

解决undefined reference to symbol ‘sem_close@@GLIBC_2.2.5‘问题

错误图示 问题原因 编译的时候&#xff0c;没有引入库文件 sem()位于pthread库中&#xff0c;所以在编译和链接时请确保使用-pthread标志&#xff0c;因此在编译的时候需要导入pthread库文件编译的顺序出现问题 解决办法 在clion的CMakeLists.txt文件中添加这一行代码set(CM…