Java | 线程start()vs run()方法 (Java | Thread start() vs run() Methods)
When we call the start() method, it leads to the creation of a new thread. Then, it automatically calls the run() method. If we directly call the run() method, then no new thread will be created. The run() method will be executed on the current thread only.
当我们调用start()方法时 ,它将导致创建新线程。 然后,它会自动调用run()方法 。 如果我们直接调用run()方法,则不会创建新线程。 run()方法将仅在当前线程上执行。
That is why we have the capability of calling the run method multiple times as it is just like any other method we create. However, the start() method can only be called only once.
这就是为什么我们能够多次调用run方法的原因,就像我们创建的任何其他方法一样。 但是,start()方法只能被调用一次。
Consider the following code:
考虑以下代码:
class MyThread extends Thread {
public void run()
{
System.out.println("Thread Running: " + Thread.currentThread().getName());
}
}
public class MyProg {
public static void main(String[] args)
{
MyThread t1 = new MyThread();
t1.start();
}
}
Output
输出量
Thread Running: Thread-0
We can clearly see that the run() method is called on a new thread, default thread being named Thread-0.
我们可以清楚地看到, run()方法是在新线程上调用的,默认线程名为Thread-0 。
Consider the following code:
考虑以下代码:
class MyThread extends Thread {
public void run()
{
System.out.println("Thread Running: " + Thread.currentThread().getName());
}
}
public class MyProg {
public static void main(String[] args)
{
MyThread t1 = new MyThread();
t1.run();
}
}
Output
输出量
Thread Running: main
We can see that in this case, we call the run() method directly. It gets called on the current running thread -main and no new thread is created.
我们可以看到在这种情况下,我们直接调用run()方法 。 在当前正在运行的线程-main上调用它,并且不创建新线程。
Similarly, in the following code, we realize that we can call the start method only once. However, the run method can be called multiple times as it will be treated as a normal function call.
同样,在下面的代码中,我们意识到只能调用一次start方法。 但是,可以多次调用run方法,因为它将被视为常规函数调用。
class MyThread extends Thread {
public void run()
{
System.out.println("Thread Running: " + Thread.currentThread().getName());
}
}
public class MyProg {
public static void main(String[] args)
{
MyThread t1 = new MyThread();
t1.run();
t1.run();
t1.start();
t1.start();
}
}
Output
输出量
Thread Running: main
Thread Running: main
Thread Running: Thread-0
Exception in thread "main" java.lang.IllegalThreadStateException
at java.base/java.lang.Thread.start(Thread.java:794)
翻译自: https://www.includehelp.com/java/thread-start-vs-run-methods-with-examples.aspx