2016-08-03 43 views
2

只是好奇我可以检查崩溃后的线程状态。到目前为止,我做了一些System.exit(0)或(1),但在我看来,线程仍然活着并且可以运行 - 期待它终止。下面是关于检查线程如何使线程崩溃或故意挂起线程?

public static void main(String[] args) { 
    Runnable runnableJob = new JobThatImplementsRunnableJob(); 
    Thread testThread = new Thread(runnableJob); 

    System.out.println("this is the testThread "+testThread.getState()); 
    System.out.println("thread is alive " + testThread.isAlive()); 
    testThread.start(); 

    System.out.println("this is the testThread after starting"+testThread.getState()); 
    System.out.println("thread is alive " + testThread.isAlive()); 

} 

和运行的类在我的测试代码,我有意地使用System.exit(1)或(0)。我也使它抛出一个错误,但仍显示线程的RUNNABLE状态。

public class JobThatImplementsRunnableJob implements Runnable { 
    public void run() { 
     System.exit(1); 
     //System.exit(0); 
     //throws Error 
    } 

} 

下面是控制台输出

this is the testThread NEW 
thread is alive false 
this is the testThread after startingRUNNABLE 
thread is alive true 

我希望上面的信息就足够了,谢谢你的建议。

+0

取代'System.exit(1)',我会添加类似'INT I = 3/0;'的'JosThatImplementsRunnableJob' – Lino

+1

你有一个竞争条件阻止你做出任何结论,也就是说,你不知道什么会先发生:主线程的最后一个System.out或者sperate线程的System.exit()。 – GPI

+0

感谢lino和GPI,线程睡眠和算术前处理技巧。 –

回答

1

当main的最后两个系统运行时,线程实际上是活动的。您需要在主线程中进行睡眠。可能是5秒钟。

+0

将System.exit(1)更改为lino评论的内容,再加上这个技巧。谢谢 –

0

System.exit()不杀死一个线程,它可以杀死你的应用程序(这是一个SYS调用,它的应用程序作为一个整体的交易,在Java线程不是内部的Java调用级别)。


你的情况看来,线程的System.exit()您的线程上第二次检查后执行(记住它运行在平行)。

0

线程不会立即开始(其实没什么用Java瞬间发生)

当你检查它可能并没有实际启动线程的状态,也没有叫System.exit(1) 。如果有的话,你不会得到输出,因为它会杀死整个过程。

不要考虑获取线程结果,而是建议将任务提交给ExecutorService。例如

Future<String> future = executorService.submit(() -> { 
    return "Success"; 
}); 

String result = future.get(); 

一个更简单的方法来提交多个作业的线程池,收集结果是使用parallelStream

List<Result> results = list.parallelStream() 
          .map(e -> process(e)) // run on all the CPUs 
          .collect(Collectors.toList()); 
1

菲利普的组合Voronov野人答案: 的你正在寻找的代码是这样的:

public class fun { 

    public static void main(String args[]) throws Exception { 
     Runnable runnableJob = new JobThatImplementsRunnableJob(); 
     Thread testThread = new Thread(runnableJob); 

     System.out.println("this is the testThread "+ testThread.getState()); 
     System.out.println("thread is alive " + testThread.isAlive()); 
     testThread.start(); 
     testThread.join(); 
     System.out.println("this is the testThread after starting "+ testThread.getState()); 
     System.out.println("thread is alive " + testThread.isAlive()); 
    } 
} 

class JobThatImplementsRunnableJob implements Runnable { 
    public void run() { 
     return; 
    } 
} 

,这里是我得到的输出:

this is the testThread NEW 
thread is alive false 
this is the testThread after starting TERMINATED 
thread is alive false 
+0

加入一个好的。谢谢 –

+0

不客气:) –