线程运行时异常行为

时间:2018-03-28 16:42:16

标签: java android multithreading runtimeexception

我用类Runnable编写了一个Thread,如下所示

class myThread implements Runnable {
public void start () {
   thread = new Thread(this, threadName);
   thread.setUncaughtExceptionHandler(handler)
   thread.start()
}
@Override
run(){
 while(toggle) { 
    try {
     //do something
    } catch {
       throw new Runtime Exception()
    }
 }
}

处理程序在另一个类

中定义
new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread thread, Throwable exception) {
                toggle = false
                try {
                    thread.start();
                } catch (Exception e) {
                    // Exception in thread
                }
                try {
                    thread.join(200);
                } catch (InterruptedException e) {

                }
                if (!thread.isAlive()){
                   // Tell Everyone Thread is Dead
                } else {
                    System.out.println("Thread is still Alive ");
                }
            }
        });

当我在华为移动中实现它时,它工作正常,thread.start,使运行功能到达终点,线程已经死了。但是在三星平板电脑中,甚至在Handler线程中的thread.join仍然是Alive之后。

问题:为什么不同设备性能不一致,API和Android版本相同

问题:抛出Runtime Exception后线程实际发生了什么?

注意:在Samsung Tablet中,thread.start的excpetion是IllegalThreadException

1 个答案:

答案 0 :(得分:0)

您的代码是荒谬的。

  • start中的Runnable方法毫无意义。它永远不会被运行Runnable
  • 的线程调用
  • 在传递给Thread#start的线程上调用uncaughtException可以保证产生IllegalThreadStateException,因为线程必须已经启动或者不会抛出异常。