python3.4 Multithreading First attempt

Source: Internet
Author: User

Inherit threading. Thread, and create 7 threads, set a local variable property, and randomly generate 8 random numbers in the run function of the thread, and use the local property to store the random number of their respective threads.

Call the start function, start the thread, and if the call to the Join function becomes serial, executes the first thread, executes the second thread sequentially, and finally executes the main thread.

(Note: Python version is 3.4)

Import Threadingimport Timeimport random# inherit threading. Thread, and reload 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, the child thread can access it, but its value is the current thread,        #如果想在当前线程保存一个全局值, and the respective threads do not interfere with each other, using the local class, 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)        #显示线程的状态, and randomly generated 10 digital        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 ()    #join函数控制线程执行顺序, do not call the Join function before start    #t. Join ()    #isDaemon函数查看线程后台运行状态    #print (T.isdaemon ()) print ("Main thread End")


python3.4 Multithreading First attempt

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.