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

วิธีการ join() ของคลาสเธรดใน Java


ฟังก์ชันการรวม

วิธีการเข้าร่วมทำให้แน่ใจว่าเธรดปัจจุบันรอจนกว่าเธรดที่ควรจะเข้าร่วมด้วยจะถูกยกเลิก ฟังก์ชันนี้รอจนกว่าเธรดที่ฟังก์ชันถูกเรียกใช้ ถูกยกเลิก

ไวยากรณ์

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