ArticleDirectory
- Merge threads
- Background thread
- Summary
Merge threads
The join () method is also provided in the Thread class of Python, so that a thread can continue to run after the execution of another thread ends. This method can also set a timeout parameter to avoid endless waiting. Because the two threads are completed in sequence and look like a thread, it is called thread merging. Example:
Import Threading
Import Random
Import Time
Class Mythread (threading. Thread ):
Def Run (Self ):
Wait_time = random. randrange (1, 10)
Print " % S will wait % d seconds " % (Self. Name, wait_time)
Time. Sleep (wait_time)
Print " % S finished! " % Self. Name
If _ Name __ = " _ Main __ " :
Threads = []
For I In Range (5 ):
T = mythread ()
T. Start ()
Threads. append (t)
Print ' Main thread is waitting for exit... '
For T In Threads:
T. Join (1)
Print ' Main thread finished! '
Execution result:
Thread-1 will wait 3 seconds
Thread-2 will wait 4 seconds
Thread-3 will wait 1 seconds
Thread-4 will wait 5 seconds
Thread-5 will wait 3 seconds
Main thread is waitting for exit...
Thread-3 finished!
Thread-1 finished!
Thread-5 finished!
Main thread finished!
Thread-2 finished!
Thread-4 finished!
Threads with too long sleep time (2 and 4 here) will not be waiting.
Background thread
By default, when the main thread exits, it waits for the end of all sub-threads. If you want the main thread to automatically end all the sub-threads when exiting without waiting for the sub-thread, you need to set the sub-thread as the background thread (Daemon ). The method is to call the setdaemon () method of the thread class. As follows:
Import Threading
Import Random
Import Time
Class Mythread (threading. Thread ):
Def Run (Self ):
Wait_time = random. randrange (1, 10)
Print " % S will wait % d seconds " % (Self. Name, wait_time)
Time. Sleep (wait_time)
Print " % S finished! " % Self. Name
If _ Name __ = " _ Main __ " :
Print ' Main thread is waitting for exit... '
For I In Range (5 ):
T = mythread ()
T. setdaemon (true)
T. Start ()
Print ' Main thread finished! '
Execution result:
Main thread is waitting for exit...
Thread-1 will wait 3 seconds
Thread-2 will wait 3 seconds
Thread-3 will wait 4 seconds
Thread-4 will wait 7 seconds
Thread-5 will wait 7 seconds
Main thread finished!
It can be seen that the main thread does not wait for the sub-thread to execute, but directly exits.
Summary
The join () method allows the thread to wait for another thread to run, while the setdaemon () method does not wait for the Child thread at the end. Both join and setdaemon can change the running sequence between threads.