This code creates 5 threads and adds them to a list called threads. Each thread calls the startThread function with a different argument i which is used to identify the thread.
The start method is called on each thread, which causes it to start executing the startThread function.
The join method is called immediately after the start method, which blocks the main thread and waits for the thread to finish executing.
from threading import Thread
from time import sleep
def startThread(n):
print("Started thread " + str(n))
sleep(1)
print("Done")
threads = []
for i in range(5):
myThread = Thread(target=startThread, args=(i,))
threads.append(myThread)
myThread.start()
myThread.join()
Started thread 0
Done
Started thread 1
Done
Started thread 2
Done
Started thread 3
Done
Started thread 4
Done
However, since the join method is called immediately after the start method, the output may not be as expected. This is because the join method blocks the main thread and waits for the thread to finish executing, so the main thread won’t start the next thread until the current thread is done. This means that only one thread will run at a time, so the output will be for one thread at a time, not all at once.
To achieve the desired output, the join method should be called outside of the loop, like this:
for i in range(5):
myThread = Thread(target=startThread, args=(i,))
threads.append(myThread)
myThread.start()
for t in threads:
t.join()
This way, the join method is called after all the threads have been started, so they will run simultaneously, and the main thread will wait for all of them to finish.