java多线程之start方法和run方法的使用区别

一、区别概述

start与run方法的主要区别在于当程序调用start方法一个新线程将会被创建,并且在run方法中的代码将会在新线程上运行,然而在你直接调用run方法的时候,程序并不会创建新线程,run方法内部的代码将在当前线程上运行。

二、分析

public class MyThread1 extends Thread {	
	@Override
	public void run() {
		try {
			System.out.println("run threadName="
					+ this.currentThread().getName() + " begin");
			Thread.sleep(2000);
			System.out.println("run threadName="
					+ this.currentThread().getName() + " end");
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		MyThread1 mythread = new MyThread1();
		
		mythread.run();
		
	}
}

上图是调用run方法的代码,结果如下图

由结果可以看出并没有创建新线程,而是main线程调用的run方法。

public class MyThread2 extends Thread {
	@Override
	public void run() {
		try {
			System.out.println("run threadName="
					+ this.currentThread().getName() + " begin ="
					+ System.currentTimeMillis());
			Thread.sleep(2000);
			System.out.println("run threadName="
					+ this.currentThread().getName() + " end   ="
					+ System.currentTimeMillis());
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		MyThread2 mythread = new MyThread2();	
		mythread.start();	
	}
}

上图是调用start方法的代码,结果如下图

由结果可以看出调用start方法后创建了新线程Thread-0。

 public synchronized void start() {
        /**
         * This method is not invoked for the main method thread or "system"
         * group threads created/set up by the VM. Any new functionality added
         * to this method in the future may have to also be added to the VM.
         *
         * A zero status value corresponds to state "NEW".
         */
        if (threadStatus != 0)
            throw new IllegalThreadStateException();

        /* Notify the group that this thread is about to be started
         * so that it can be added to the group's list of threads
         * and the group's unstarted count can be decremented. */
        group.add(this);

        boolean started = false;
        try {
            start0();//调用native方法执行线程run方法
            started = true;
        } finally {
            try {
                if (!started) {
                    group.threadStartFailed(this);
                }
            } catch (Throwable ignore) {
                /* do nothing. If start0 threw a Throwable then
                  it will be passed up the call stack */
            }
        }
    }
上面是start方法的源码,可以看到start方法调用了start0()方法来执行线程的run方法,

猜你喜欢

转载自blog.csdn.net/chenbingbing111/article/details/79899077