多个线程是可以操作同一个全局变量的,因此,可以通过这种方式来判断所有线程的执行进度
# 第一种方法:将要执行的方法作为参数传给Thread的构造方法 import threading import time liste = ["a","s","v","dd","ee"] def action(a): print threading.currentThread() time.sleep(2) liste.remove(a) print liste print("-------------") if __name__ == "__main__": for item in liste: a = threading.Thread(target = action, args = (item,)) a.start()
# 第二种方法:从Thread继承,并重写run() #!-*- coding:utf-8 -*- import threading import time liste = ["a","s","v","dd","ee"] class myThread(threading.Thread): def __init__(self, arg): # threading.Thread.__init__(self) # 这2种方法都可以使用 super(myThread, self).__init__() self.arg = arg def run(self):# 这个函数定义每个线程要执行的代码,可以嵌套函数 self.action() def action(self): print threading.currentThread() time.sleep(2) liste.remove(self.arg) print(liste) print("-------------") if __name__ == "__main__": for item in liste: a = myThread(item) a.start()