Java – why does the execution order between printstacktrace () and other methods seem uncertain?

In the following code snippet, the printStackTrace () method is called in the catch block. After running the program, you can see that sometimes printstacktrace() runs several times in succession instead of in the order of printstacktrace() – > catch block – > is finally blocked

If you change static Boolean B to false, system out. Print (E) is executed sequentially

So why does printstacktrace () run differently? (things with threads?)

public class PrintStackTrace {
    static boolean b = true;
    public static void main(String[] args){
        for(int i = 0; i < 100; i++){
            try{
                throw new Exception("[" + i + "]");
            }
            catch(Exception e){
                if(b){
                    e.printStackTrace();
                }
                else{
                    System.out.print(e);
                }
                System.out.print(" Catch: " + i);
            }
            finally{
                System.out.print(" Finally: " + i);
            }
            System.out.println();
        }
    }
}

Solution

This is because when system out. Println in system When writing on out, printstacktrace is in system Write in err Even system Err and system Out all use the same underlying resources to output messages (such as the same file or the same console), and they will also be refreshed at different times

If you want to get synchronous output, please go to system Write exception in out:

e.printStackTrace(System.out);

Or better, use the logger, which has synchronized the output to the shared resource, and provides you with more options about the output content in the message, such as class, method, date and time, thread name, etc., as well as other benefits such as writing log messages in the database instead of text files

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>