多线程run()与start()的区别

使用start()时:

public static void main(String[] args){
        Thread thread=new Thread(new Runnable() {
            public void run() {
                for(int i=0;i<10;i++){
                    System.out.println(i);
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        thread.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("fin");
        return;
    }

结果为:
使用start()结果
使用run()时:

public static void main(String[] args){
        Thread thread=new Thread(new Runnable() {
            public void run() {
                for(int i=0;i<10;i++){
                    System.out.println(i);
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        thread.run();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("fin");
        return;
    }

结果为:
使用run()结
结论:
调用线程的start方法是创建了新的线程。
调用线程的run方法是在主线程中执行该方法,和调用普通方法一样。

附1:
debug时需ctrl+shift+f8将All换成Thread
附2:
调试发现主线程return后线程仍在继续执行,查资料得知:

java程序运行于jvm中,jvm会开启一个守护线程,这个线程会在没有任何非守护线程的时候才停止程序。所以main函数return,导致主线程结束之后,工作线程仍然是在运行的。这些非守护线程的存在,会使得java程序一直运行着。

猜你喜欢

转载自blog.csdn.net/yinzitun7947/article/details/84347729