ฟังก์ชันการรวม
ฟังก์ชันนี้ใช้เพื่อรวมจุดเริ่มต้นของการดำเนินการของเธรดไปยังจุดสิ้นสุดของการดำเนินการของเธรดอื่น วิธีนี้จะทำให้มั่นใจได้ว่าเธรดแรกจะไม่ทำงานจนกว่าเธรดที่สองจะหยุดดำเนินการ ฟังก์ชันนี้จะรอให้เธรดสิ้นสุดในจำนวนมิลลิวินาทีที่ระบุ
เรามาดูตัวอย่างกัน −
ตัวอย่าง
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 ใช้คลาส Runnable ฟังก์ชัน 'run' ถูกกำหนดให้เธรดปัจจุบันเป็นเธรดที่สร้างขึ้นใหม่ ในฟังก์ชันหลัก อินสแตนซ์ใหม่ของเธรดจะถูกสร้างขึ้น และเริ่มใช้ฟังก์ชัน 'start' หรือไม่ เธรดนี้ถูกรวมเข้ากับเธรดอื่นหลังจากระยะเวลาที่กำหนด ข้อความที่เกี่ยวข้องจะแสดงบนหน้าจอ