ตัวอย่าง
public class Main{
static volatile boolean exit = false;
public static void main(String[] args){
System.out.println("Starting the main thread");
new Thread(){
public void run(){
System.out.println("Starting the inner thread");
while (!exit){
}
System.out.println("Exiting the inner thread");
}
}.start();
try{
Thread.sleep(100);
}
catch (InterruptedException e){
System.out.println("Exception caught :" + e);
}
exit = true;
System.out.println("Exiting main thread");
}
} ผลลัพธ์
Starting the main thread Starting the inner thread Exiting main thread Exiting the inner thread
คลาสหลักสร้างเธรดใหม่และเรียกใช้ฟังก์ชัน 'run' ในที่นี้ ค่าบูลีนถูกกำหนด ชื่อ 'exit' ซึ่งตั้งค่าเป็นเท็จในตอนแรก นอกวง while ฟังก์ชัน 'start' จะถูกเรียก ในบล็อกการลอง เธรดที่สร้างขึ้นใหม่จะเข้าสู่โหมดสลีปเป็นระยะเวลาหนึ่งหลังจากนั้นจะตรวจพบข้อยกเว้น และข้อความที่เกี่ยวข้องจะแสดงบนหน้าจอ หลังจากนี้ เธรดหลักจะถูกปิดเนื่องจากค่าของ exit จะถูกตั้งค่าเป็น 'จริง'