我們可以在 Java 中直接呼叫 run() 方法而不是 start() 嗎?
是的,我們可以做到。讓我們看一個示例 -
示例
class my_thread extends Thread{
public void run(){
try{
System.out.println ("The thread " + Thread.currentThread().getId() + " is currently running");
}
catch (Exception e){
System.out.println ("The exception has been caught");
}
}
}
public class Main{
public static void main(String[] args){
int n = 6;
for (int i=1; i<n; i++){
my_thread my_object = new my_thread();
my_object.run();
}
}
}輸出
The thread 1 is currently running The thread 1 is currently running The thread 1 is currently running The thread 1 is currently running The thread 1 is currently running
一個名為“my_thread”的類繼承了主執行緒,其中定義了一個“run”函式,該函式給出正在執行的當前執行緒的 ID。定義了一個 try and catch 塊,該塊捕獲異常(如果有)並顯示相關的錯誤。在主函式中,執行一個“for”迴圈並建立“my_thread”類的新的物件。針對此物件呼叫“run”函式。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
安卓
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP