Posts

Showing posts from May, 2023

Thread Termination and Demon Thread

Image
 Thread Termination: Why : Because Thread are Consuming Resources : Like Memory, Kernel Recourses, cpu Cycle and cache memory When: 1. if thread finished its work, so we need to clean up the thread's resources 2. if thread misbehaving  3. By default application will not stope the thread as long as at least one thread is still running  Therad.intrrupt(): 1 if the thread is executing a method that throws an intrrupedException 2. if the thread's code is handling the interrupt signal explicitly  3.  If any one of the thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), calling the Thread.interrupt() method on the thread, breaks out the sleeping or waiting state throwing InterruptedException. If the thread is not in the sleeping or waiting state, calling the interrupt() method performs normal behavior and doesn't interrupt the thread but sets the interrupt flag to true   Daemon Thread: Daemon threads are thread that do not prevent the...

How to Create Threads in Java

Image
How to Create Thread There are two ways to Create Thread  1 Extending Thread Class public class ThreadClass extends Thread { @Override public void run() { System . out .println( "Thread Running Thread " +Thread. currentThread ().getName()); } } 2. Runnable Interface public class RunnableClass implements Runnable { @Override public void run() { System. out .println( "Runnable Running Thread " +Thread. currentThread ().getName()); } } Main Class how to Call the Thread and Runnable Threads public class Main { public static void main(String[] args ) { ThreadClass tClass = new ThreadClass(); tClass .start(); RunnableClass rClass = new RunnableClass(); Thread rThread = new Thread( rClass ); rThread .start(); } }    Both will Create the Similar Thread but there are some Advantages as Runnable Interface are 1.  Less memory required for Runnable Interface 2.  If a class is implementing the runnable interface then ...