Thread ส่งสัญญาณ interrupt โดยเรียก interrupt() บนอ็อบเจกต์ Thread เป้าหมาย หมายถึง thread อื่นเรียก interrupt() ให้ thread นั้น
เมธอด interrupt สำคัญ 3 เมธอด
- void interrupt() - ส่งสัญญาณ interrupt ให้ thread
- static boolean interrupted() - ตรวจสอบ thread ปัจจุบันถูก interrupt หรือไม่ (และเคลียร์ flag)
- boolean isInterrupted() - ตรวจสอบ thread นี้ถูก interrupt หรือไม่ (ไม่เคลียร์ flag)
ตัวอย่าง: หยุด Thread ด้วย interrupt
public class ThreadInterruptTest {
public static void main(String[] args) {
System.out.println("Thread main started");
final Task task = new Task();
final Thread thread = new Thread(task);
thread.start();
thread.interrupt(); // ส่งสัญญาณ interrupt
System.out.println("Main Thread finished");
}
}
class Task implements Runnable {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("[" + Thread.currentThread().getName() + "] Message " + i);
if (Thread.interrupted()) { // ตรวจสอบและเคลียร์ flag
System.out.println("This thread was interrupted by someone calling Thread.interrupt()");
System.out.println("Cancelling task running in thread " + Thread.currentThread().getName());
System.out.println("After Thread.interrupted() call, JVM reset the interrupted value to: " + Thread.interrupted());
break;
}
}
}
}
ผลลัพธ์
Thread main started
Main Thread finished
[Thread-0] Message 0
This thread was interrupted by someone calling Thread.interrupt()
Cancelling task running in thread Thread-0
After Thread.interrupted() call, JVM reset the interrupted value to: false
จุดสำคัญ: interrupt() ไม่หยุด thread ทันที - thread ต้องตรวจสอบ flag และตัดสินใจหยุดเอง (cooperative cancellation)