Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Cách tạo thread không implement Runnable interface trong Java?

Thread là tiết trình nhẹ (lightweight process). Java hỗ trợ đa luồng (multithreading), cho phép ứng dụng thực hiện hai hoặc nhiều tác vụ đồng thời. Mọi chương trình Java có ít nhất một thread gọi là main thread, do JVM tạo khi main() được gọi. Có hai cách tạo thread: kế thừa Thread class hoặc implement Runnable interface.

Cũng có thể tạo thread không implement Runnable như dưới:

Ví dụ

public class CreateThreadWithoutImplementRunnable { 
    // không implements Runnable 
    public static void main(String[] args) { 
        new Thread(new Runnable() { 
            public void run() { 
                for (int i = 0; i <= 5; i++) { 
                    System.out.println("run() method of Runnable interface: " + i); 
                } 
            } 
        }).start(); 
        for (int j = 0; j <= 5; j++) { 
            System.out.println("main() method: " + j); 
        } 
    } 
}

Kết quả

main() method: 0 run() method of Runnable interface: 0 main() method: 1 run() method of Runnable interface: 1 main() method: 2 run() method of Runnable interface: 2 main() method: 3 run() method of Runnable interface: 3 main() method: 4 run() method of Runnable interface: 4 main() method: 5 run() method of Runnable interface: 5