2014-05-02 17 views
0
杀死一个线程

我在一个类中创建一个线程,代码如下无法在Android的

private void startThread() { 
    if (t != null) { 
     t.interrupt(); 
    } 
    isFlashOn = true; 

    t = new Thread() { 
     public void run() { 
      try { 
       try { 
        SurfaceView surfaceView = (SurfaceView) activity 
          .findViewById(R.id.surfaceViewCam); 
        SurfaceHolder surfaceHolder = surfaceView.getHolder(); 
        // surfaceHolder.addCallback(this); 
        camera.setPreviewDisplay(surfaceHolder); 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 

       camera.startPreview(); 

       for (int i = seekBarManager.preferenceManager 
         .get_duration(); i > 0 && !this.isInterrupted(); i--) { 
        isFlashOn = true; 
        setBlinkToggle(); 
        sleep(seekBarManager.preferenceManager.get_delay()); 
        if(isFlashOn==false){ 
         break; 
        } 
       } 

       if (camera != null) { 
        camera.stopPreview(); 
        camera.release(); 
        camera = null; 
       } 

      } catch (Exception e) { 
       e.printStackTrace(); 
      } 

     } 
    }; 

    t.start(); 
} 

我停止线程的方法

private void stopThread() { 
    if (t != null) { 
     t.interrupt(); 
     //t. 
     isFlashOn = false; 
    } 
} 

的问题,我面对是,线程中的for循环似乎仍在运行,即使在成功调用后Interrupt()

任何帮助在这里将不胜感激!

更新的代码

t = new Thread() { 
      public void run() { 
       Boolean isStop = false; 
       try { 
        try { 
         SurfaceView surfaceView = (SurfaceView) activity 
           .findViewById(R.id.surfaceViewCam); 
         SurfaceHolder surfaceHolder = surfaceView.getHolder(); 
         // surfaceHolder.addCallback(this); 
         camera.setPreviewDisplay(surfaceHolder); 
        } catch (Exception e) { 
         e.printStackTrace(); 
        } 

        camera.startPreview(); 

        for (int i = seekBarManager.preferenceManager 
          .get_duration(); i > 0 && !isStop; i--) { 
         isFlashOn = true; 
         setBlinkToggle(); 
         sleep(seekBarManager.preferenceManager.get_delay()); 
        } 

        if (camera != null) { 
         camera.stopPreview(); 
         camera.release(); 
         camera = null; 
        } 

       } catch (Exception e) { 
        e.printStackTrace(); 
        isStop=true; 
        //notify(); 
        return; 
       } 

      } 
     }; 

回答

0

中断的目的(): 它只是规定了中断标志设置为true。在调用interrupt()之后,Thread.currentThread()。isInterrupted()开始返回false。就这样。

另一种情况是,如果在调用引发InterruptedException的某个方法中阻塞线程时调用interrupt(),那么该方法将返回抛出InterruptedException。如果线程的代码只是“吃掉”那个异常,那么线程仍然会继续运行。

所以正确的做法应该是定期检查中断标志。如果检测到中断状态,则只需返回ASAP。另一个常见的选择是根本不使用Thread.interrupt(),而是使用一些自定义布尔值。

请参见下面的链接,线程的安全停止: -

http://www.java2s.com/Code/Java/Threads/Thesafewaytostopathread.htm

+0

亲爱的贝蒂迪瓦恩,我已经做了必要的修改。但仍然线程继续运行。我是否需要在catch块中委派Interrupted异常? –

+1

您是否可以在for循环中添加一个条件来检查线程是否中断,然后中断循环? –

+0

我确实尝试过。我现在面临的问题是,在DEBUG模式下,一切正常。但是当我运行线程时,它失败了。 –