ใช่ เราสามารถทำได้ เรามาดูตัวอย่างกัน −
ตัวอย่าง
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' ถูกเรียกบนวัตถุนี้