2012-02-23 38 views
4

我必须使用可运行的这样一个类内部实现线程:停止并重新运行一个线程里面本身

static Runnable myThread = new Runnable() { 
public void run(){ 
    try{ 
    //do something forever 
    }catch(Exception e){ 
    //something happened. Re-run this thread 
    } 
} 
} 

我想继续运行这个线程即使有异常发现。那么,我怎样才能在异常条款中做到这一点?有没有更优雅的解决方案?

+0

是否有一个循环内的尝试?难道它不在try-catch之外吗? – Jivings 2012-02-23 18:19:27

回答

6

使用一个循环:

static Runnable myThread = new Runnable() { 
    public void run() { 
    for (;;) { 
     try { 
     ... 
     } catch(Exception e) { 
     ... 
     } 
    } 
    } 
} 

不管你做什么,我会强烈建议您不要忽略这些异常。如果没有更好的方法来处理异常,至少应该记录它。

3

你可以做一段时间并继续循环。例如:

public void run() { 
    while (true) 
     try { 
      // do something forever 
     } catch(Exception e) { 
     // something happened. Re-run this thread 
     continue; 
     } 
     ... 
    } 
}