Java多线程中start和run方法的区别

39 阅读1分钟

start()run()方法的主要区别在于:

  • 当程序调用start()方法,一个新线程将会被创建,并且在run()方法中的代码会在新线程上运行。

  • 当直接调用run()方法时,程序并不会创建新线程,run()方法内部的代码在当前线程上运行。

【示例】

public class DifferentBetweenStartAndRun {
    public static void main (String[] args) {
        ThreadTask startThread = new ThreadTask("start");
        ThreadTask runThread = new ThreadTask("run");

        new Thread(startThread).start();
        new Thread(runThread).run();
    }

    public static class ThreadTask implements Runnable {
        private String caller;

        public ThreadTask(String caller) {
            this.caller = caller;
        }

        @Override
        public void run () {
            System.out.println("Caller: " + caller + ";  Thread is " + Thread.currentThread().getName());
        }
    }
}

// 打印如下
// Caller: run;  Thread is main
// Caller: start;  Thread is Thread-0