Code Explanation:
1️⃣ Importing Module
import threading
Explanation
This line imports the threading module.
The threading module allows Python to run multiple threads (tasks) concurrently.
Threads help execute parts of a program simultaneously.
2️⃣ Defining the Function
def task():
Explanation
A function named task is created.
This function will be executed inside a separate thread.
3️⃣ Loop Inside the Function
for i in range(2):
Explanation
A loop runs 2 times.
range(2) generates numbers:
0, 1
4️⃣ Printing Values
print(i)
Explanation
Each iteration prints the value of i.
So the function prints:
0
1
5️⃣ Creating a Thread
t = threading.Thread(target=task)
Explanation
A Thread object is created.
target=task means the thread will execute the task() function.
At this point, the thread is created but not started yet.
6️⃣ Starting the Thread
t.start()
Explanation
This starts the thread.
The thread begins executing the task() function.
The function prints:
0
1
7️⃣ Waiting for Thread to Finish
t.join()
Explanation
join() tells the main program to wait until the thread finishes.
Without join(), the program might print "Done" before the thread finishes.
8️⃣ Printing Final Statement
print("Done")
Explanation
After the thread finishes, the main program prints:
Done
๐ค Final Output
0
1
Done

0 Comments:
Post a Comment