我有两个线程 A和B,我需要它俩不停的运行.Thread A =new Thread(new ZteQZJClientFmSocket(socketServer, socketFmPort, rawDataRing));
A.start();Thread B =new Thread(new ZteQZJClientFmSocket(socketServer, socketFmPort, rawDataRing));
B.start();A B线程内比较复杂,有时候会断掉.我能不能再写一个线程C监控A和B的运行,一旦A和B断掉,C就让A和B重新运行起来?问题两天没解决,请大家帮忙.
A.start();Thread B =new Thread(new ZteQZJClientFmSocket(socketServer, socketFmPort, rawDataRing));
B.start();A B线程内比较复杂,有时候会断掉.我能不能再写一个线程C监控A和B的运行,一旦A和B断掉,C就让A和B重新运行起来?问题两天没解决,请大家帮忙.
调用处理程序的 uncaughtException 方法,将线程和异常作为参数传递。如果某一线程没有明确设置其 UncaughtExceptionHandler,则将它的 ThreadGroup 对象作为其 UncaughtExceptionHandler。如果 ThreadGroup 对象对处理异常没有什么特殊要求,那么它可以将调用转发给默认的未捕获异常处理程序。
是否对你有帮助
public class ThreadTest {
public static void main(String[] args) {
ErrHandler handle = null;
ThreadA a = null;
a = new ThreadA();
handle = new ErrHandler();
a.setUncaughtExceptionHandler(handle);// 加入定义的ErrHandler
a.start();
}
}
/**
* 自定义的一个UncaughtExceptionHandler
*/
class ErrHandler implements UncaughtExceptionHandler {
/**
* 这里可以做任何针对异常的处理,比如记录日志等等
*/
public void uncaughtException(Thread a, Throwable e) {
System.out.println("This is:" + a.getName() + ",Message:"
+ e.getMessage());
e.printStackTrace();
}
}
/**
* 拥有UncaughtExceptionHandler的线程
*/
class ThreadA extends Thread {
public ThreadA() {
}
public void run() {
double i = 12 / 0;// 抛出异常的地方
}
}
Thread thread = new Thread(new ZteQZJClientFmSocket(socketServer, socketFmPort, rawDataRing));
thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread t, Throwable e) {
System.out.println("重新启动线程...");
start(socketServer, socketFmPort, rawDataRing);
}
});
thread.start();
private void start(final Object socketServer, final Object socketFmPort, final Object rawDataRing) {
Thread thread = new Thread(new ZteQZJClientFmSocket(socketServer, socketFmPort, rawDataRing));
thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread t, Throwable e) {
System.out.println("重新启动线程...");
start(socketServer, socketFmPort, rawDataRing); // 调用本身
}
});
thread.start();
}