python原生的线程类实例:
import threading from time import ctime,sleep def music(songs,time): for i in range(time): print("第{}次播放music{}!时间是{}".format(i,songs,ctime())) sleep(2) def moive(moives,time): for i in range(time): print("第{}次播放movie{}!时间是{}".format(i,moives,ctime())) sleep(5) threads=[] t1 = threading.Thread(target=music, args=('love',2)) threads.append(t1) t2 = threading.Thread(target=moive, args=('小大夫',2)) threads.append(t2) if __name__ =="__main__": for th in threads: th.start() #守护线程 for t in threads: t.join() print('all end:{}'.format(ctime()))封装自定义的线程类
import threading from time import ctime,sleep class MyThread(threading.Thread): def __init__(self, func, args, name=""): threading.Thread.__init__(self) self.func = func self.args = args self.name = name def run(self): self.func(*self.args) def super_play(files, time): for i in range(2): print("start palying:{}!{}".format(files,ctime())) sleep(time) lists = {"love.mp3":3, "sunshine.mp3":2, "世界这么大":2} threads = [] files = len(lists) for file,time in lists.items(): t = MyThread(super_play, (file, time), super_play.__name__) threads.append(t) if __name__ == "__main__": for i in range(files): threads[i].start() for j in range(files): threads[j].join() print("all end {}".format(ctime()))