原创

java面试题-线程Thread类中start()与run()区别

在Java中,多线程编程是一项重要的技能,而Thread类的start()方法和run()方法是多线程编程中经常涉及的两个关键方法。在本教程中,我们将深入探讨这两个方法的区别,并通过详细的代码示例帮助初学者理解它们的用法。

1. start()方法与run()方法的区别

1.1 start()方法

start()方法是Thread类中的一个重要方法,用于启动一个新线程。当start()方法被调用时,会在新线程中执行run()方法。这个过程是由Java虚拟机(JVM)自动管理的。

1.2 run()方法

run()方法是Thread类中的另一个方法,包含了线程的执行逻辑。但需要注意的是,直接调用run()方法并不会开启新线程,而是在当前线程中执行run()方法的内容。

2. 使用示例

为了更好地理解start()run()方法的区别,我们将通过示例代码进行演示。

2.1 使用start()方法

public class StartRunExample extends Thread {

    public void run() {
        for (int i = 1; i <= 5; i++) {
            System.out.println("Thread using start(): " + i);
            try {
                Thread.sleep(500);  // 模拟线程执行中的延迟
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        StartRunExample thread = new StartRunExample();
        thread.start();  // 启动新线程
    }
}

在上述示例中,通过调用start()方法,我们成功启动了一个新线程,该线程执行了run()方法的内容。

2.2 使用run()方法

public class StartRunExample extends Thread {

    public void run() {
        for (int i = 1; i <= 5; i++) {
            System.out.println("Thread using run(): " + i);
            try {
                Thread.sleep(500);  // 模拟线程执行中的延迟
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        StartRunExample thread = new StartRunExample();
        thread.run();  // 直接调用run()方法,不会开启新线程
    }
}

在这个示例中,通过直接调用run()方法,线程的执行发生在主线程中,并没有开启新的线程。

3. 区别总结

通过以上示例,我们总结start()run()方法的区别:

  • start()方法会启动一个新线程,并在新线程中执行run()方法的内容。
  • run()方法直接调用不会开启新线程,而是在当前线程中执行run()方法的内容。
正文到此结束
本文目录