jstack 用于導出java應用程式的線程堆棧。
jstack -l pid
jstatck工具會輸出程式中所有的鎖資訊,可以使用重定向将輸出儲存檔案。
jstack -l pid > C:\deadLock.txt
package test;
import java.util.concurrent.locks.ReentrantLock;
public class DeadLock extends Thread{
protected Object myDirect;
static ReentrantLock south=new ReentrantLock();
static ReentrantLock north=new ReentrantLock();
public DeadLock(Object obj){
this.myDirect=obj;
if(myDirect==south){
this.setName("south");
}
if(myDirect==north){
this.setName("north");
}
}
@Override
public void run(){
if(myDirect=="south"){
try{
north.lockInterruptibly(); //占用north
try{
Thread.sleep(500);
}catch(Exception e){
e.printStackTrace();
}
south.lockInterruptibly(); //占用south
System.out.println("car to south has passed");
}catch(Exception e1){
System.out.println("cat to south is killed");
}finally{
if(north.isHeldByCurrentThread())
north.unlock();
if(south.isHeldByCurrentThread())
south.unlock();
}
}
if(myDirect=="north"){
try{
south.lockInterruptibly(); //占用south
try{
Thread.sleep(500);
}catch(Exception e){
e.printStackTrace();
}
north.lockInterruptibly(); //占用north
System.out.println("car to north has passed");
}catch(Exception e1){
System.out.println("cat to north is killed");
}finally{
if(north.isHeldByCurrentThread())
north.unlock();
if(south.isHeldByCurrentThread())
south.unlock();
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
DeadLock car2sourth=new DeadLock(south);
DeadLock car2north=new DeadLock(north);
car2sourth.start();
car2north.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}