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

Java Concurrency - เมธอด join()

เมธอด join()

เมธอดนี้ใช้รวมการเริ่มต้นการทำงานของ thread หนึ่งกับการสิ้นสุดของอีก thread หนึ่ง ทำให้มั่นใจได้ว่า thread แรกจะไม่รันจนกว่า thread ที่สองจะหยุดทำงานแล้ว เมธอดนี้รอเป็นจำนวน milliseconds ที่กำหนดให้ thread สิ้นสุดการทำงาน

ตัวอย่าง

import java.lang.*;

public class Demo implements Runnable {
    public void run() {
        Thread my_t = Thread.currentThread();
        System.out.println("The name of the current thread is " + my_t.getName());
        System.out.println("Is the current thread alive? " + my_t.isAlive());
    }

    public static void main(String args[]) throws Exception {
        Thread my_t = new Thread(new Demo());
        System.out.println("The instance has been created and started");
        my_t.start();
        my_t.join(30);
        System.out.println("The threads will be joined after 30 milli seconds");
        System.out.println("The name of the current thread is " + my_t.getName());
        System.out.println("Is the current thread alive? " + my_t.isAlive());
    }
}

ผลลัพธ์

The instance has been created and started
The threads will be joined after 30 milli seconds
The name of the current thread is Thread-0
The name of the current thread is Thread-0
Is the current thread alive? true
Is the current thread alive? true

คลาส Demo implements Runnable กำหนดเมธอด run() ดึง thread ปัจจุบัน ใน main สร้าง thread ใหม่ เริ่มด้วย start() เรียก join(30) รอ 30 ms แสดงข้อมูล thread