日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

Java线程start()vs run()方法及示例

發布時間:2025/3/11 java 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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.

當我們調用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-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

總結

以上是生活随笔為你收集整理的Java线程start()vs run()方法及示例的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。