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