我有两个线程 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重新运行起来?问题两天没解决,请大家帮忙.

解决方案 »

  1.   

    当某一线程因未捕获的异常而即将终止时,Java 虚拟机将使用 Thread.getUncaughtExceptionHandler() 
    调用处理程序的 uncaughtException 方法,将线程和异常作为参数传递。如果某一线程没有明确设置其 UncaughtExceptionHandler,则将它的 ThreadGroup 对象作为其 UncaughtExceptionHandler。如果 ThreadGroup 对象对处理异常没有什么特殊要求,那么它可以将调用转发给默认的未捕获异常处理程序。
    是否对你有帮助
      

  2.   

    笨办法,不知道对不对C类里需要有A、B两个类的引用,C线程定时查询A、B两个类的isAlive方法,如果A、B线程未处于活动状态,就重启A、B线程
      

  3.   

    import java.lang.Thread.UncaughtExceptionHandler;
     
    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;// 抛出异常的地方
      }
     
    }
      

  4.   


            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();
      

  5.   

    不好意思没写全,下面的才是:
    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();
    }