[英]How to make a Java thread hang
我正在尝试创建一个解决方案,以处理由于内存泄漏,我们的应用程序中的锁定资源而导致的挂起线程。 我遇到的一个主要问题是尝试模拟一个挂起的线程来处理它。 任何sugestions?
这是我尝试过的,但它似乎没有做到这一点。 有什么想法吗?
class KillerThread extends Thread{
public KillerThread() {
super();
}
public KillerThread(String threadName) {
super(threadName);
}
public void run (){
System.out.println("Start of KillerThread " + this.getName() );
if ( System.currentTimeMillis() % 2L == 0 ){
try {
sleep(Long.MAX_VALUE);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
for(;;);
}
}
}
尝试在while循环中运行sleep,如:
while(true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
加入自己的线程对我来说很有用:
Thread.currentThread().join();
这是我用于测试的快速修复。 只需让你想要锁定的线程调用new Hanger().hang()
。
如果您对查看不感兴趣,请删除日志记录。 您可以向throws InterruptedException
方法添加throws InterruptedException
(尽管事实上它永远不Thread.sleep()
,这样您就可以用new Hanger().hang()
替换Thread.sleep()
new Hanger().hang()
而无需修改代码。
public class Hanger {
private final static Logger log = Logger.getLogger(Hanger.class);
private long started = 0;
private final int beat = 100; // ms
/**
* Hangs a thread for the indicated time
* @param millis the amount of time to hang the thread, in milliseconds
*/
public void hang(int millis) {
started = System.currentTimeMillis();
log.debug("Hanging this thread for " + millis + " ms");
while (hung() < millis) {
try {
Thread.sleep(beat);
} catch (InterruptedException e) {
log.debug("Still hanging, will release in " + (millis - hung()) + " ms.");
}
}
log.debug("Releasing thread again after " + hung() + " ms");
}
private int hung() {
return (int)(System.currentTimeMillis() - started);
}
}
运行一个线程然后告诉它在一个不可阻挡的循环中睡觉,是个好主意。 但是如果你试图让它等待另一个线程怎么办? 制作多个线程并使它们彼此等待,一个死锁状态,是一个挂起来的。
简单来说,只需创建一个私人成员
private Object lock = new Object();
然后用它来等待通知(除非你使用反射,否则永远不会发生通知......)
while (true) {
try {
synchronized (lock) {
lock.wait();
}
} cath (InterruptedException e) {
/* ignore interruption */
}
}
而你的线程将挂在那里,不间断。
我完全知道你需要什么,你通过停止执行程序线程来测试一些东西。 尝试这样的事情:
private void testKillingThread() {
Object kill = new Object();
try {
synchronized (kill) {
kill.wait();
}
} catch (Exception e) {
// Auto-generated catch block
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.