Skip to content

Commit f082dc0

Browse files
committed
feat: add Thread2 demo with sleep and join for sequential execution
WHAT the code does: - Defines Thread2 extending Thread. - Overrides run(): - Loops from 1 to 5, sleeping 5 seconds between each iteration. - Prints the counter and a final message ("Thread is running....."). - In main(): - Creates a Thread2 object. - Starts the thread with start(). - Calls join() to ensure main waits until t2 finishes. WHY this matters: - Demonstrates thread lifecycle with controlled execution order. - join() ensures the main thread does not exit before the child thread completes. - Thread.sleep() introduces artificial delay to visualize scheduling and thread control. HOW it works: 1. t2.start() → JVM schedules run() in a separate thread. 2. run() executes: - For each iteration, sleeps for 5s (TIMED_WAITING state). - After waking, prints the current counter. 3. After loop, prints completion message. 4. main thread waits due to join(), preventing premature termination. Use-case: - Useful when you want tasks to complete in strict sequence. - Demonstrates the difference between concurrent execution and forced synchronization with join(). Short key: java-threads sleep-join sequential-demo. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent 09f8fac commit f082dc0

File tree

1 file changed

+8
-11
lines changed

1 file changed

+8
-11
lines changed
Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,21 @@
1-
class Thread2 extends Thread
2-
{
3-
@Override // Thread class ka overridden method. Thread class Methods.
4-
public void run()
5-
{
1+
class Thread2 extends Thread {
2+
@Override
3+
// Thread class ka overridden method. Thread class Methods.
4+
public void run() {
65
for (int i =1; i<=5; i++){
7-
try{
6+
try {
87
Thread.sleep(5000);
98
}
10-
catch(InterruptedException e)
11-
{
9+
catch(InterruptedException e) {
1210
throw new RuntimeException(e);
1311
}
1412
System.out.println(i);
1513
}
1614
System.out.println("Thread is running.....");
1715
}
18-
public static void main(String[] args) throws InterruptedException
19-
{
16+
public static void main(String[] args) throws InterruptedException {
2017
Thread2 t2 = new Thread2();
2118
t2.start();
2219
t2.join();
2320
}
24-
}
21+
}

0 commit comments

Comments
 (0)