ThreadMXBean
常用方法:
/** ThreadMXBean常用方法test */
ThreadMXBean threadMXBean= ManagementFactory.getThreadMXBean();
int count=threadMXBean.getThreadCount();//获取当前线程数目
System.out.println("当前线程数为:"+count);
long[] threadIds=threadMXBean.getAllThreadIds();
System.out.println("当前线程id们为:"+ JSONObject.toJSONString(threadIds));
ThreadInfo[] threadInfos=threadMXBean.getThreadInfo(threadMXBean.getAllThreadIds());
System.out.println("当前线程的信息:"+JSONObject.toJSONString(threadInfos));
System.out.println("是否支持测量线程执行时间:"+threadMXBean.isCurrentThreadCpuTimeSupported());
/**
* 死锁检测工具
* Created by liuhuichao on 2017/6/21.
*/
public class DeadLockCheckChecker {
private final static ThreadMXBean mbean=ManagementFactory.getThreadMXBean();
final static Runnable deadLockCheck=new Runnable() {
@Override
public void run() {
while (true){
long[] deadLockedThreadIds=mbean.findDeadlockedThreads();
if(deadLockedThreadIds!=null){
ThreadInfo[] threadInfos=mbean.getThreadInfo(deadLockedThreadIds);
for(Thread t: Thread.getAllStackTraces().keySet()){
for(int i=0;i<threadInfos.length;i++){
if(t.getId()==threadInfos[i].getThreadId()){
t.interrupt();
}
}
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}
};
public static void check(){
Thread thread=new Thread(deadLockCheck);
thread.setDaemon(true);
thread.start();
}
}
可中断性测试:
/**ReentrantLock可中断性测试
* Created by liuhuichao on 2017/6/20.
*/
public class ReentrantLockInterruptedTest implements Runnable {
public static ReentrantLock lock1=new ReentrantLock();
public static ReentrantLock lock2=new ReentrantLock();
int lock;
/**
* 控制加锁顺序,方便构造死锁
* @param lock
*/
public ReentrantLockInterruptedTest(int lock) {
this.lock = lock;
}
@Override
public void run() {
try{
if(lock==1){
lock1.lockInterruptibly();
try{
Thread.sleep(500);
}catch (InterruptedException e){}
lock2.lockInterruptibly();
}else{
lock2.lockInterruptibly();
try{
Thread.sleep(500);
}catch (InterruptedException e){}
lock1.lockInterruptibly();
}
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
if(lock1.isHeldByCurrentThread()){
lock1.unlock();
}
if(lock2.isHeldByCurrentThread()){
lock2.unlock();
}
System.out.println("线程退出:"+Thread.currentThread().getId());
}
}
public static void main(String[] args) throws Exception{
ReentrantLockInterruptedTest l1=new ReentrantLockInterruptedTest(1);
ReentrantLockInterruptedTest l2=new ReentrantLockInterruptedTest(2);
Thread t1=new Thread(l1);
Thread t2=new Thread(l2);
t1.start();
t2.start();
Thread.sleep(1000);
DeadLockCheckChecker.check();
}
}