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

Tầm quan trọng của phương thức join() trong Java?

join() là phương thức final của lớp Thread dùng để nối đầu thực thi của một thread với cuối thực thi của thread khác, sao cho thread không chạy cho đến khi thread kia kết thúc. Nếu join() được gọi trên instance thread, luồng hiện tại sẽ block cho đến khi instance thread đó kết thúc.

Cú pháp

public final void join() throws InterruptedException

Ví dụ

public class JoinTest extends Thread { 
    public void run() { 
        for(int i = 1; i <= 3; i++) { 
            try { 
                Thread.sleep(1000); 
            } catch(Exception e) { 
                System.out.println(e); 
            } 
            System.out.println("TutorialsPoint " + i); 
        } 
    } 
    
    public static void main(String args[]) { 
        JoinTest t1 = new JoinTest(); 
        JoinTest t2 = new JoinTest(); 
        JoinTest t3 = new JoinTest(); 
        t1.start(); 
        try { 
            t1.join(); // gọi join()  
        } catch(Exception e) { 
            System.out.println(e); 
        } 
        t2.start(); 
        t3.start(); 
    } 
}

Kết quả

TutorialsPoint 1 TutorialsPoint 2 TutorialsPoint 3 TutorialsPoint 1 TutorialsPoint 1 TutorialsPoint 2 TutorialsPoint 2 TutorialsPoint 3 TutorialsPoint 3