记一次简单的线程死锁调优
如果是内存调优,请看我以前一篇博文 http://www.cnblogs.com/springsource/archive/2013/01/11/2856968.html
调优演示
1. 先写一个死锁小程序,如下
package com.he.jin.bin; /** * QQ 277803242 * * @author 何锦彬 2014.1.29 * * 线程死锁演示调优 * */ public class Test4DeadLock extends Thread { public static Object obj1 = new Object(); public static Object obj2 = new Object(); public static void main(String[] args) { new Thread(new Runnable() { public void run() { synchronized (obj1) { System.out.println("have in obj1 lock"); try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("wait for obj2 lock"); synchronized (obj2) { System.out.println("lock2 have been done"); } } } }).start(); new Thread(new Runnable() { @Override public void run() { synchronized (obj2) { System.out.println("have in obj2 lock"); try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("wait for obj1 lock"); synchronized (obj1) { System.out.println("lock1 have been done"); } } } }).start(); } }
运行,输出如下,被死锁
have in obj1 lock have in obj2 lock wait for obj1 lock wait for obj2 lock
为了发现这个死锁, 可以先用JDK自带工具 JPS查看所有JAVA进程
C:\Users\Administrator>jps
6048 Jps
5304 Test4DeadLock
1376 org.eclipse.equinox.launcher_1.3.0.v20130327-1440.jar
发现线程死锁的进程ID
用jstack -l 5404 ,打印出死锁描述
C:\Users\Administrator>jstack -l 5304
2014-01-29 10:19:28
Full thread dump Java HotSpot(TM) 64-Bit Server VM (24.51-b03 mixed mode):
"DestroyJavaVM" prio=6 tid=0x00000000025cd800 nid=0x143c waiting on condition [0
x0000000000000000]
java.lang.Thread.State: RUNNABLE
Locked ownable synchronizers:
- None
"Thread-1" prio=6 tid=0x000000000a23a800 nid=0x11e4 waiting for monitor entry [0
x000000000ac3e000]
java.lang.Thread.State: BLOCKED (on object monitor)
at com.he.jin.bin.Test4DeadLock$2.run(Test4DeadLock.java:39)
- waiting to lock <0x00000000eb519e78> (a java.lang.Object)
- locked <0x00000000eb519e88> (a java.lang.Object)
at java.lang.Thread.run(Unknown Source)
Locked ownable synchronizers:
- None
"Thread-0" prio=6 tid=0x000000000a239800 nid=0xd64 waiting for monitor entry [0x
000000000a9cf000]
java.lang.Thread.State: BLOCKED (on object monitor)
at com.he.jin.bin.Test4DeadLock$1.run(Test4DeadLock.java:20)
- waiting to lock <0x00000000eb519e88> (a java.lang.Object)
- locked <0x00000000eb519e78> (a java.lang.Object)
at java.lang.Thread.run(Unknown Source)
Locked ownable synchronizers:
- None
附上 JDK其它调优命令
http://blog.csdn.net/feihong247/article/details/7874063
<script>
alert("test");
</script>