ฟังก์ชัน 'ขัดจังหวะ' สามารถใช้ใน Java เพื่อขัดจังหวะการทำงานของเธรดด้วยความช่วยเหลือของข้อยกเว้น InterruptedException
ตัวอย่างด้านล่างแสดงให้เห็นว่าเธรดที่รันอยู่หยุดการทำงานอย่างไร (เนื่องจากมีข้อยกเว้นใหม่ในบล็อก catch) เมื่อถูกขัดจังหวะ -
ตัวอย่าง
public class Demo extends Thread
{
public void run()
{
try
{
Thread.sleep(150);
System.out.println("In the 'run' function inside try block");
}
catch (InterruptedException e)
{
throw new RuntimeException("The thread has been interrupted");
}
}
public static void main(String args[])
{
Demo my_inst = new Demo();
System.out.println("An instance of the Demo class has been created");
my_inst.start();
try
{
my_inst.interrupt();
}
catch (Exception e)
{
System.out.println("The exception has been handled");
}
}
} ผลลัพธ์
An instance of the Demo class has been created Exception in thread "Thread-0" java.lang.RuntimeException: The thread has been interrupted at Demo.run(Demo.java:12)
คลาสชื่อ Demo ขยายคลาสเธรด ที่นี่ ภายในบล็อก 'ลอง' มีการกำหนดฟังก์ชันชื่อ 'เรียกใช้' ที่ทำให้ฟังก์ชันอยู่ในโหมดสลีปเป็นเวลา 150 มิลลิวินาที ในบล็อก "จับ" ข้อยกเว้นถูกตรวจพบและข้อความที่เกี่ยวข้องจะแสดงบนคอนโซล
ในฟังก์ชันหลัก อินสแตนซ์ของคลาสสาธิตจะถูกสร้างขึ้น และเธรดจะเริ่มต้นโดยใช้ฟังก์ชัน 'เริ่ม' ภายในบล็อก "ลอง" อินสแตนซ์ถูกขัดจังหวะ และในบล็อก "จับ" ข้อความที่เกี่ยวข้องซึ่งระบุข้อยกเว้นจะถูกพิมพ์