We handle the InterruptedException in the below program with a try and catch block, so that anytime another thread interrupts the presently operating thread, it would wake up but not stop functioning.
package DockerTpoint; class ThreadClass extends Thread { public void run(){ try{ for (int i = 0; i < 3; i++) { System.out.println("ThreadClass Thread is running"); // The current thread is put to sleep, and another thread is given the opportunity to execute. Thread.sleep(1000); } } catch (InterruptedException e) { e.printStackTrace(); } } } class Main { public static void main(String[] args)throws InterruptedException{ ThreadClass thread = new ThreadClass(); thread.start(); thread.interrupt(); System.out.println("The main thread has finished its execution."); } }
Output:
The main thread has finished its execution.
ThreadClass Thread is running
java.lang.InterruptedException: sleep interrupted
In the program below, after interrupting the currently executing thread, we throw a new exception in the catch block, causing it to stop working.
package DockerTpoint; class ThreadClass extends Thread { public void run(){ try{ Thread.sleep(1000); System.out.println("ThreadClass"); } catch (InterruptedException e) { throw new RuntimeException("Thread interrupted"+e); } } } class Main { public static void main(String[] args)throws InterruptedException{ ThreadClass thread = new ThreadClass(); thread.start(); try { thread.interrupt(); } catch (Exception e) { e.printStackTrace(); } } }
Output:
Exception in thread "Thread-0" java.lang.RuntimeException: Thread
interruptedjava.lang.InterruptedException: sleep interrupted
In the program below, after interrupting the currently executing thread, we throw a new exception in the catch block, causing it to stop working.
class ThreadClass extends Thread { public void run(){ for (int i = 1; i <= 10; i++) { System.out.println("5 * "+i+" = "+5*i); } } } class Main { public static void main(String[] args){ ThreadClass thread = new ThreadClass(); thread.start(); thread.interrupt(); } }
Output:
5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50
Police Colony
Patna, Bihar
India
Email:
Post your comment