#! /Usr/bin/ENV Python # Coding = UTF-8 # Source: Python core programming multithreading chapter import threadingfrom time import ctime, sleep, time''' use the instance creation method using the threading multi-threaded method to create two threads, familiar with the basic operations of the thread ''' # create a thread instance, pass it a function secds = [] # def loop (nloop, secds) of the pause time of each thread: Print 'the loop ', nloop, 'started', ctime () sleep (secds) print 'the loop ', nloop, 'stoped', ctime () # maindef main (): Print 'mian thread started', ctime () threads = [] nloops = range (LEN (secds) # create an instance of all threads for I in nloops: threadins = threading. thread (target = loop, argS = (I, secds [I]) # threads cannot be omitted for target and other parameters. append (threadins) # Start all sub-threads in sequence for I in nloops: threads [I]. start () # Wait until all threads end for I in nloops: threads [I]. join () print 'all threads done', ctime () If _ name __= = '_ main _': Main () ''' # create a thread, it is passed to a callable Class Object. This time, the method is passed into the object, which is rarely used. This is a problem in testing # Program Yes, but what is d? I still don't understand ''' secds = [] # class threadfun (object) corresponding to the sub-thread ): def _ init _ (self, argS): Self. ARGs = ARGs def _ call _ (Self): # automatically call apply (self. loop, self. ARGs) def loop (D, nloop, nsec): # This call method adds a parameter # print Dir (d) # print tpye (d) # tpye not defined !! Print '\-' * 20 print 'loop', nloop, 'start', ctime () sleep (nsec) print 'loop', nloop, 'stop', ctime () def main (): Print 'start: ', ctime () threads = [] nloops = range (LEN (secds) for I in nloops: t = threading. thread (target = threadfun (I, secds [I]) threads. append (t) for I in nloops: threads [I]. start () # Start all threads for I in nloops: threads [I]. join () # Wait For All threads done print 'all thread done', ctime () If _ name __= = '_ main _': Main () ''' # The following is one of our most common methods, namely, implementing multi-threading of inheritance classes # This references tutorialspoint Code Exitflag = 0 class mythread (threading. thread): # inherit from threading. thread def _ init _ (self, threadid, name, counter): threading. thread. _ init _ (Self) self. threadid = threadid self. name = Name self. counter = counter def run (Self): Print "starting" + self. name print_time (self. name, self. counter, 6) # print "exiting" + self. namedef print_time (threadname, delay, counter): While counter: If exitflag: thread. exit () sleep (Delay) print "% s: % s" % (threadname, ctime (Time () Counter-= 1 # create new threadsthread1 = mythread (1, "thread-1", 1) thread2 = mythread (2, "thread-2", 2) # Start new threadsthread1.start () thread2.start () print "exiting main thread" # Another common module is queue.