Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

เมธอด join() ของ Thread Class ใน Java

เมธอด join() ทำให้ thread ปัจจุบันรอจนกว่า thread ที่จะ join จะสิ้นสุดการทำงาน (terminated) เมธอดนี้จะรอจนกว่า thread ที่เรียกฟังก์ชันจะ terminated

Syntax

final void join() throws InterruptedException

ตัวอย่าง

public class Demo extends Thread {
    public void run() {
        System.out.println("sample ");
        try {
            Thread.sleep(10);
        } catch (InterruptedException ie) {
        }
        System.out.println("only ");
    }

    public static void main(String[] args) {
        Demo my_obj_1 = new Demo();
        Demo my_obj_2 = new Demo();
        my_obj_1.start();
        System.out.println("The first object has been created and started");
        try {
            System.out.println("In the try block, the first object has been called with the join function");
            my_obj_1.join();
        } catch (InterruptedException ie) {
        }
        System.out.println("The second object has been started");
        my_obj_2.start();
    }
}

ผลลัพธ์

The first object has been created and started
In the try block, the first object has been called with the join function
sample
only
The second object has been started
sample
only

คลาส Demo extends Thread มี run() พิมพ์ "sample" sleep 10ms แล้วพิมพ์ "only" ใน main สร้าง 2 อ็อบเจ็กต์ เริ่ม obj_1 เรียก join() รอจนเสร็จ แล้วค่อยเริ่ม obj_2