উদাহরণ
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' নামক একটি বুলিয়ান মান সংজ্ঞায়িত করা হয়েছে, যা প্রাথমিকভাবে false সেট করা হয়েছে। একটি while লুপের বাইরে 'start' ফাংশন কল করা হয়েছে। try ব্লকে নতুন তৈরি থ্রেড নির্দিষ্ট সময় ধরে স্লিপ করে, এরপর এক্সেপশন ক্যাচ করা হয় এবং প্রাসঙ্গিক মেসেজ স্ক্রিনে দেখানো হয়। এরপর মেইন থ্রেড বন্ধ হয় কারণ exit-এর মান 'true' সেট করা হয়েছে।