使用工具jconsole和visualvm
jconsole可以查看内存状况和死锁
内存泄露代码
package com.test;
import java.util.*;
public class Heap{
public static void main(String[] args) throws InterruptedException{
ArrayList list=new ArrayList();
Integer count = 0;
Thread.sleep(30000);
System.out.print("start");
while(true){
//System.out.println("第次"+ ++count +"进入循环-----");
Thread.sleep(50);
list.add(new Heap());
}
}
}
死锁代码
package com.test;
public class SynAddRunable {
static class synRun implements Runnable {
int a;
int b;
public synRun(int a, int b) {
this.a = a;
this.b = b;
}
@Override
public void run() {
// Integer.valueOf(a) 会换存-128~127的数字,实际就返回了2和3两个对象
synchronized (Integer.valueOf(a)) {
// 假如在两个synchronized之间发生了线程切换,那就会出现线程a等待线程b的(Integer.valueOf(b))对象,
// 而线程b又等待线程a的(Integer.valueOf(a))的对象,结果都跑不下去了,线程卡住,都等不了对方释放锁了
synchronized (Integer.valueOf(b)) {
System.out.println(a + " + " + b + "=" + (a + b));
}
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread.sleep(30000);// 30秒,有空余时间来启动,jconsole,并链接这个java进程
System.out.println("start------");
// 200个线程
for (int i = 0; i < 100; i++) {
new Thread(new synRun(2, 3)).start();
new Thread(new synRun(3, 2)).start();
}
System.out.println("end------");
Thread.sleep(10000000);// 一直停顿,方便查看数据
}
}
线程等待代码
package com.test;
import java.io.*;
public class BusyThread {
/**
* 线程死循环演示
*/
public static void createBusyThread() {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
while (true) // 第41行
;
}
}, "testBusyThread");
thread.start();
}
/**
* 线程锁等待演示
*/
public static void createLockThread(final Object lock) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}, "testLockThread");
thread.start();
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
br.readLine();
createBusyThread();
br.readLine();
Object obj = new Object();
createLockThread(obj);
}
}
visualvm查看堆dump排查内存泄露
线程死锁
jconsole