在聊Jstack得工作原理前呢,不如让我们先写一个简单的jstack玩玩。不用怕,很简单的,就几行代码的事,看:
public class MyJstack { public static void main(String[] args)throws Exception { VirtualMachine virtualMachine = VirtualMachine.attach("6361"); HotSpotVirtualMachine hotSpotVirtualMachine = (HotSpotVirtualMachine)virtualMachine; InputStream inputStream = hotSpotVirtualMachine.remoteDataDump(new String[]{}); byte[] buff = new byte[256]; int len; do { len = inputStream.read(buff); if (len > 0) { String respone = new String(buff, 0, len, "UTF-8"); System.out.print(respone); } } while(len > 0); inputStream.close(); virtualMachine.detach(); } }