In run method, how to find from where start was called?

◇◆丶佛笑我妖孽 提交于 2020-01-24 12:22:30

问题


I am debugging some code. My debugger shows that the origin of code is from Thread.run(). I need to know from which part of code Thread.start() was called! Is there a way to find this out?


回答1:


You can use new Throwable().getStackTrace() to get a full stack trace. To get the start stack you must extend Thread, one of the few times it is actually necessary to do so (mostly using Runnable is preferred).

class C extends Thread {
    StackTraceElement[] constructed;
    StackTraceElement[] started;

    public C() {
        constructed = new Throwable().getStackTrace();
    }

    @Override
    public void run() {
        // Your suuff.
    }

    @Override
    public synchronized void start() {
        started = new Throwable().getStackTrace();
        super.start();
    }

}



回答2:


I found a crude and effective technique using Eclipse or any other IDE. Suppose you have a breakpoint in your Runnable or Callable, and thread pauses there... no double one can't figure out from where start was called right away... but, just right click Runnable/Callable constructor and click 'show call hierarchy'.. that's it!! YOu will come to know where the Runnable/Callable was constructed.. and start is called right after that!
In Eclipse, if Runnable/Callable has no no-arg constructor, right click on class name and select 'show call hierarchy'.. problem solved.. what a relief.



来源:https://stackoverflow.com/questions/34905333/in-run-method-how-to-find-from-where-start-was-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!