from random import randintimport threadingfrom time import ctime, sleepdata = [' A ', ' B ', ' C ', ' d ', ' e ', ' f ', ' g ', ' h ', ' I ', ' J ']class mythread (threading. Thread): lock = threading. Lock () def __init__ (self, task): super (mythread, self). __init__ () self.task = task def run (self): print ("in time:{} Start Function:{} ". Format (CTime (), self.task.__name__) self.lock.acquire () self.task () self.lock.release () Def a (): # Modify the elements in the list from the back to the for i in data[::-1]: new_val = ' xxx%s ' % (Randint (100, 150)) index = Data.index (i) data[index] = new_val print ("original value:{} with index:{} modified to:{}". Format (i, index, new_val)) def b (): #从前往后依次读取列表 For i in data: print ("Read Value:{} index:{} ". Format (I, data.index (i))) Def main (): funcs = [a, b] threads = [] loop = range (Len (funcs)) for i in loop: t = MyThread (Funcs[i])  &NBSp; threads.append (t) for i in loop: threads[i].start () for i in loop: threads[i].join () if __name__ == ' __ Main__ ': main () print (" all done!!!")
Python thread synchronization