importthreadingclassMyThread1(threading.Thread):defrun(self):local=threading.local()if‘name‘notinlocal.__dict__:print(‘thread1 not set name‘)local.name=‘li‘print(‘thread1 {}‘.format(local.name))classMyThread2(threading.Thread):defrun(self):local=threading.local()if‘name‘notinlocal.__dict__:print(‘thread2 not set name‘)local.name=‘wang‘print(‘thread2 {}‘.format(local.name))defmain():print("Start main threading")local=threading.local()local.name=‘main‘threads=[MyThread1(),MyThread2()]fortinthreads:t.start()# 一次让新创建的线程执行 joinfortinthreads:t.join()print(‘main {}‘.format(local.name))if__name__==‘__main__‘:main()
其最后的输出结果为:
Start main threadingthread1 not set namethread1 lithread2 not set namethread2 wangmain main
2. Thread Obects
函数
class threading.Thread(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None)