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

1、start()和run()的区别说明

start():它的作用是启动一个新线程,新线程会执行相应的run()方法。start()不能被重复调用。

run():run()和普通的成员方法一样,可以被重复调用,单独调用run(),会在当前线程中执行run(),而不会启动新线程

class MyThread extends Thread
{
    public void run()
    {
        ...
    }
}

MyThread mt = new MyThread();

mt.start()会启动一个新线程,并在新线程中运行run()方法

而mt.run()则会直接在当前线程中运行run()方法,并不会启动一个新线程来运行run()

2、start()和run()的区别示例

class MyThread extends Thread
{
    public MyThread(String name)
    {
        super(name);
    }
    public void run()
    {
        System.out.println(Thread.currentThread().getName()+" is running");
    }
}

public class problem1 
{    
    public static void main(String[] args)
    {
        MyThread mt =  new MyThread("mythread");
        System.out.println(Thread.currentThread().getName()+" call mythread,run");
        
        mt.run();
        
        System.out.println(Thread.currentThread().getName()+ " call mythread.start()");
        
        mt.start();
    }
}

运行结果:

main call mythread,run
main is running
main call mythread.start()
mythread is running

结果说明:

(1)、Thread.currentThread().getName()获取当前线程的名字。当前线程是指正在CPU中调度运行的线程

(2)、mt.run()是在主线程main中调用的,该run()方法直接运行在主线程main上

(3)、mt.start()会启动线程mythread,线程mythread启动之后,会调用run方法,此时的run()方法运行在线程mythread上

3、start()和run()的相关源码

Thread.java中的start()方法的源码如下:

public synchronized void start() {
    // 如果线程不是"就绪状态",则抛出异常
    if (threadStatus != 0)
        throw new IllegalThreadStateException();

    // 将线程添加到ThreadGroup中
    group.add(this);

    boolean started = false;
    try {
        // 通过start0()启动线程
        start0();
        // 设置started标记
        started = true;
    } finally {
        try {
            if (!started) {
                group.threadStartFailed(this);
            }
        } catch (Throwable ignore) {
        }
    }
}

说明:start()通过本地方法start0()启动线程。start0()会新运行一个线程,该线程会调用run()方法

private native void start0();

Thread.java中的run()代码如下:

public void run()
{
    if(target != null)
        target.run();
}

说明:target是一个Runnable对象。run()就是直接调用Thread线程的Runnable成员的run()方法,并不会新建一个线程

就是直接调用Thread线程的Runnable成员的run
[Jiùshì zhíjiē diàoyòng Thread xiànchéng de Runnable chéngyuán de run]
Is a direct call to the members Thread Runnable thread's run
原文地址:https://www.cnblogs.com/qumasha/p/12824887.html