java中关于抛出异常的输出顺序问题

以下纯属个人拙见,如有不妥,还望海涵

public class Demo{
    public static void main(String[] args) {
        Thread t = new Thread(new MyRunnable());
        t.setName("t");
        t.start();
        //睡眠5秒
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //中段t线程的睡眠
        t.interrupt();
    }
}

class MyRunnable implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"--->begin");
        try {
            Thread.sleep(1000*60);
        } catch (InterruptedException e) {
            e.printStackTrace();
            System.out.println("测试");
        }
        System.out.println(Thread.currentThread().getName()+"--->end");
    }
}

输出:
![在这里插入图片描述]( https://img-blog.csdnimg.cn/20200602001101620.png?x-oss-process=image/watermark ,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTMzNDAyMg==,size_16,color_FFFFFF,t_70)

  • 删掉main方法中的睡眠5秒的代码后:
public class Demo{
    public static void main(String[] args) {
        Thread t = new Thread(new MyRunnable());
        t.setName("t");
        t.start();
        //中段t线程的睡眠
        t.interrupt();
    }
}

class MyRunnable implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"--->begin");
        try {
            Thread.sleep(1000*60);
        } catch (InterruptedException e) {
            e.printStackTrace();
            System.out.println("测试");
        }
        System.out.println(Thread.currentThread().getName()+"--->end");
    }
}

输出:
![在这里插入图片描述]( https://img-blog.csdnimg.cn/20200602001219207.png?x-oss-process=image/watermark ,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTMzNDAyMg==,size_16,color_FFFFFF,t_70)
这里的异常按理说应该在中间输出,但是跑到了后面。原因如下:

  • 控制台的两种输出方式
    1、控制台的输出方式总共两种,分别是:
    正常输出:System.out.println();
    发生错误时的输出:System.err.println();
  • 所以原因可能是:
    错误输出延迟打印到控制台了。
posted @ 2020-06-02 00:21  YU_UY  阅读(664)  评论(0)    收藏  举报