Working of Thread States 1. New State :- The thread is created but not started yet. 2. Runnable State:- The thread is ready to run and waiting for CPU time. 3. Running State:- The CPU is currently executing the thread’s code. 3.Blocked / Waiting State:- The thread is not running because it’s waiting for something: Waiting for another thread to complete (join()). Sleeping for a time (sleep()). Blocked waiting for a resource . 4.Terminated State:- The thread has finished its task. It cannot be restarted. The thread is ready to run and waiting for CPU time.
1. By Extending the Thread Class class MyThread extends Thread { public void run() { System.out.println ("Thread is running..."); } public static void main(String[] args ) { MyThread t1 = new MyThread (); t1.start(); } }
2. By Implementing the Runnable Interface class MyRunnable implements Runnable { public void run() { System.out.println ("Thread is running using Runnable..."); } public static void main(String[] args ) { MyRunnable obj = new MyRunnable (); Thread t1 = new Thread( obj ); t1.start(); } }
How Thread Synchronization Works In Java Synchronization means controlling the access of multiple threads to shared resources. When a thread enters a synchronized method/block, it acquires the lock . Other threads trying to access the same method/block must wait until the lock is released. Once the thread finishes execution, it releases the lock , allowing another thread to enter.
1. Synchronized Method Locks the entire method allowing only one thread to acess it at a time. Example: class Table { synchronized void printTable (int n) { for(int i =1; i <=5; i ++) System.out.println (n * i ); } } class MyThread extends Thread { Table t; int num ; MyThread (Table t, int num ) { this.t = t; this.num = num ; } public void run() { t.printTable ( num ); } } public class Test { public static void main(String[] args ) { Table obj = new Table(); new MyThread ( obj , 5).start(); new MyThread ( obj , 100).start(); } }
2. Synchronized Block It locks only a specific part of the code using an object as a lock. Example class Table { void printTable (int n) { synchronized(this) { for(int i =1; i <=5; i ++) { System.out.println (n * i ); }}}} class MyThread extends Thread { Table t; int num ; MyThread (Table t, int num ) { this.t = t; this.num = num ; } public void run() { t.printTable ( num ); } } public class Test { public static void main(String[] args ) { Table obj = new Table(); new MyThread ( obj , 5).start(); new MyThread ( obj , 10).start(); }}