Java线程start()vs run()方法及示例
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.
當(dāng)我們調(diào)用start()方法時(shí) ,它將導(dǎo)致創(chuàng)建新線程。 然后,它會(huì)自動(dòng)調(diào)用run()方法 。 如果我們直接調(diào)用run()方法,則不會(huì)創(chuàng)建新線程。 run()方法將僅在當(dāng)前線程上執(zhí)行。
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.
這就是為什么我們能夠多次調(diào)用run方法的原因,就像我們創(chuàng)建的任何其他方法一樣。 但是,start()方法只能被調(diào)用一次。
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-0We can clearly see that the run() method is called on a new thread, default thread being named Thread-0.
我們可以清楚地看到, run()方法是在新線程上調(diào)用的,默認(rèn)線程名為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: mainWe 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.
我們可以看到在這種情況下,我們直接調(diào)用run()方法 。 在當(dāng)前正在運(yùn)行的線程-main上調(diào)用它,并且不創(chuàng)建新線程。
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.
同樣,在下面的代碼中,我們意識(shí)到只能調(diào)用一次start方法。 但是,可以多次調(diào)用run方法,因?yàn)樗鼘⒈灰暈槌R?guī)函數(shù)調(diào)用。
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-0Exception in thread "main" java.lang.IllegalThreadStateExceptionat java.base/java.lang.Thread.start(Thread.java:794)翻譯自: https://www.includehelp.com/java/thread-start-vs-run-methods-with-examples.aspx
總結(jié)
以上是生活随笔為你收集整理的Java线程start()vs run()方法及示例的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [转载] Python的生成器
- 下一篇: java scanner_Java Sc