Python3.4 multithreading first attempt
Inherit from threading. thread, and create 7 threads, set a local variable attribute, and generate 8 random numbers randomly in the Thread's run function, and store the random numbers of their respective threads using the local attribute.
Call the start function to start the thread. If the join function is called, it becomes serial. After the first thread is executed, the second thread is executed in sequence, and the main thread is executed.
(Note: python version 3.4)
Import threadingimport timeimport random # inherits threading. Thread and reloads the run function. Class jdThread (threading. thread): def _ init _ (self, num): threading. thread. _ init _ (self) self. num = num self. create_time = time. time () self. local = threading. local () # local has global access. The main thread and sub-thread can access it, but its value is related to the current thread. # If you want to save a global value in the current thread, and the respective threads do not interfere with each other. The local class is used. Actually, it is a dictionary def run (self): self. local = [] time. sleep (1) print ("Thread", self. num, "created") for I in range (8): self. local. append (random. randrange (10) # displays the thread status and the randomly generated 10 numbers print (threading. currentThread (), self. local) print (time. time ()-self. create_time) print ("Thread", self. num, "end") print ("\ n") print ("main thread start") for item in range (7): t = jdThread (item) t. start () # The join function controls the thread execution sequence. Do not call the join function before start # t. join () # view the running status of the thread background using the isDaemon function # print (t. isDaemon () print ("main thread ends ")