JAVA-MULTITHREADING_E-2
Thread Lifecycle, Methods & Practical Examples
🔴 public final boolean isAlive()
- When we call
start()method → a new thread is created in a separate Stack Memory. - Thread class provides a predefined non-static method:
public final boolean isAlive()- Return type →
boolean
Used to verify:
- Whether a thread has started or not
- Whether the thread is alive or not
Behavior:
- If the thread is not started →
isAlive()returnsfalse - If the thread is started and running → returns
true - If the thread completed execution → returns
false
⚠ In Java, we cannot restart a thread.
If we try → Runtime Exception:
java.lang.IllegalThreadStateExceptionExample 1
package com.ravi.basic;
class Test extends Thread
{
@Override
public void run()
{
System.out.println("Child thread is running...");
System.out.println("It is running with separate stack memory");
}
}
public class IsAliveDemo
{
public static void main(String[] args) throws InterruptedException
{
System.out.println("Main thread started!!!!");
Test t1 = new Test();
System.out.println("Is thread started OR Alive before start :
"+t1.isAlive());
t1.start();
System.out.println("Is thread started OR Alive after start :
"+t1.isAlive());
Test t2 = new Test();
t2.start();
t1.start(); // java.lang.IllegalThreadStateException
}
}🔴 Thread Name & Exception Demo
package com.ravi.basic;
class Foo extends Thread
{
@Override
public void run()
{
String name = Thread.currentThread().getName();
System.out.println(name+" thread is running...");
}
}
public class ExceptionDemo
{
public static void main(String[] args)
{
String name = Thread.currentThread().getName();
System.out.println(name+" thread is running!!!!");
Foo f1 = new Foo();
f1.start();
Foo f2 = new Foo();
f2.start();
System.out.println(10/0); // Exception
System.out.println(name+" thread completed");
}
}NOTE:
If the main thread is interrupted due to an ArithmeticException,
child threads will still execute because they run in separate stack memory.
🔴 Thread Loop Example
package com.ravi.basic;
class Sample extends Thread
{
@Override
public void run()
{
String name = Thread.currentThread().getName();
for(int i=1; i<=10; i++)
{
System.out.println(i+" by "+name+" thread");
}
}
}
public class ThreadLoop
{
public static void main(String[] args)
{
new Sample().start();
String name = Thread.currentThread().getName();
for(int i=1; i<=10; i++)
{
System.out.println(i+" by "+name+" thread");
}
int x = 1;
do
{
System.out.println("India");
x++;
}
while(x<=10);
}
}NOTE:
The processor frequently switches between the main thread & Thread-0.
So the output is unpredictable.
Get Aman Verma’s stories in your inbox
Join Medium for free to get updates from this writer.
The thread scheduler decides which thread executes first.
🔴 How to Set and Get Thread Name
By default JVM assigns names:
Thread-0
Thread-1
Thread-2Methods:
public final synchronized void setName(String name)
public final String getName()Example 1 (Default Names)
package com.ravi.basic;
class DoStuff extends Thread
{
@Override
public void run()
{
String name = Thread.currentThread().getName();
System.out.println("Running Thread name is : "+name);
}
}
public class ThreadName1
{
public static void main(String[] args)
{
DoStuff d1 = new DoStuff();
d1.start();
DoStuff d2 = new DoStuff();
d2.start();
System.out.println("Current thread name is :
"+Thread.currentThread().getName());
}
}Example 2 (User-Defined Names)
package com.ravi.basic;
class Demo extends Thread
{
@Override
public void run()
{
String name = Thread.currentThread().getName();
System.out.println("Running Thread name is : "+name);
}
}
public class ThreadName2
{
public static void main(String[] args)
{
Thread t = Thread.currentThread();
t.setName("Parent");
Demo d1 = new Demo();
Demo d2 = new Demo();
d1.setName("Child1");
d2.setName("Child2");
d1.start();
d2.start();
System.out.println("Current thread name is :"+t.getName());
}
}🔴 Batch Assignment Example
package com.ravi.basic;
class BatchAssignment extends Thread
{
@Override
public void run()
{
String name = Thread.currentThread().getName();
if(name != null && name.equalsIgnoreCase("Placement"))
{
this.placementBatch();
}
else if(name != null && name.equalsIgnoreCase("Regular"))
{
this.regularBatch();
}
else
{
throw new NullPointerException("Name can't be null");
}
}
public void placementBatch()
{
System.out.println("I am a placement batch student.");
}
public void regularBatch()
{
System.out.println("I am a Regular batch student.");
}
}public class ThreadName3
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
try(sc)
{
System.out.println("Enter your Batch Title [Placement/Regular]
:");
String title = sc.next();
BatchAssignment b = new BatchAssignment();
b.setName(title);
b.start();
}
catch(InputMismatchException e)
{
System.out.println("Invalid Input");
}
}
}🔴 Thread.sleep(long millis)
public static void sleep(long millis) throws InterruptedException- Static method of the Thread class
- Puts the thread into a temporary waiting/sleeping state
- Time is given in milliseconds
Example:
Thread.sleep(1000); // sleeps for 1 secondMust handle using:
- try-catch
OR - throws InterruptedException
Example 1
package com.ravi.sleep;
class Sleep extends Thread
{
@Override
public void run()
{
String name = Thread.currentThread().getName();
for(int i=1; i<=10; i++)
{
System.out.println(i+" value is :-"+i+" by "+name+" thread");
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println(e);
}
}
}
}
public class SleepDemo1
{
public static void main(String[] args)
{
Sleep s = new Sleep();
s.setName("Child");
s.start();
}
}Example 2
class MyTest extends Thread
{
@Override
public void run()
{
for(int i=1; i<=5; i++)
{
System.out.println("i value is :"+i);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
}
public class SleepDemo2
{
public static void main(String[] args)
{
MyTest m1 = new MyTest();
MyTest m2 = new MyTest();
m1.setName("M1");
m2.setName("M2");
m1.start();
m2.start();
}
}threadId() Method (JDK 19+)- Introduced in JDK 19
- Returns the unique ID of the current thread
- Defined in the Thread class
- Final method
long id = Thread.currentThread().threadId();Example
package com.ravi.sleep;
class MyThread1 extends Thread
{
@Override
public void run()
{
System.out.println("Child Thread is running");
Thread t = Thread.currentThread();
System.out.println("Id of child thread is :"+t.threadId());
}
}
public class SleepDemo3
{
public static void main(String[] args)
{
System.out.println("Main thread is Started");
Thread t = Thread.currentThread();
System.out.println("Id of main thread is :"+t.getId());
MyThread1 mt = new MyThread1();
mt.start();
try
{
Thread.sleep(4000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
System.out.println("Main thread is Ended");
}
}MPORTANT DIFFERENCES (Console Points)start()→ creates a new thread
run()→ normal method call (no new thread)isAlive()→ checks thread running status- Cannot restart thread → IllegalThreadStateException
sleep()is a static methodgetId()→ old method
threadId()→ introduced in JDK 19- Output order is unpredictable due to the Thread Scheduler









