Có, chúng ta có thể làm điều đó. Xem ví dụ:
Ví dụ
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(); } } }
Kết quả
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
Lớp my_thread kế thừa Thread, định nghĩa hàm run in ID luồng hiện tại. Khối try-catch bắt ngoại lệ và in lỗi. Trong main, vòng lặp for tạo đối tượng mới của my_thread và gọi run trên đối tượng đó.