线程类的start()方法可以用来启动线程;该方法会在内部调用Runnable接口的run()方法,以在单独的线程中执行run()方法中指定的代码。
start()方法启动线程执行以下任务:
线程类的run()方法是Runnable接口的一个抽象方法,由java虚拟机直接调用的,不会创建的新线程。
class MyThread extends Thread {
public void run() {
System.out.println("\n");
System.out.println("当前线程的名称: " + Thread.currentThread().getName());
System.out.println("run()方法调用");
}
}
class demo {
public static void main(String[] args) {
MyThread t = new MyThread();
t.start();
}
}
输出:
正如我们在上面的例子中所看到的,当我们调用线程类实例的start()方法时,会创建一个新的线程,默认名称为Thread-0,然后调用run()方法,并在其中执行所有内容。新创建的线程。
现在,让我们尝试直接调用run()方法而不是start()方法:
class MyThread extends Thread {
public void run() {
System.out.println("\n");
System.out.println("当前线程的名称: " + Thread.currentThread().getName());
System.out.println("run()方法调用");
}
}
class GeeksforGeeks {
public static void main(String[] args) {
MyThread t = new MyThread();
t.run();
}
}
输出:
正如我们在上面的例子中所看到的,当我们调用MyThread类的run()方法时,没有创建新线程,并且在当前线程即主线程上执行run()方法。因此,没有发生多线程。run()方法是作为正常函数被调用。
https://baijiahao.baidu.com/s?id=1624067920453033349&wfr=spider&for=pc
多线程 - Thread.start() vs Thread.run()
原文:https://www.cnblogs.com/frankcui/p/12434430.html