defthread1(): for i in range(2): print("The thread name is {} and start in {}".format(threading.current_thread().name,ctime())) sleep(1) print("The thread name is {} and end in {}".format(threading.current_thread().name,ctime()))
defthread2(): for i in range(2): print("The thread name is {} and start in {}".format(threading.current_thread().name,ctime())) sleep(1) print("The thread name is {} and end in {}".format(threading.current_thread().name,ctime()))
for t in threads: print(t.daemon) t.start() print("The thread name is {} and end in {}".format(threading.current_thread().name,ctime())) # result: 最后一个线程退出,用时两秒。 ''' False The thread name is Thread-1 and start in Fri Jun 29 16:34:43 2018 False The thread name is Thread-2 and start in Fri Jun 29 16:34:43 2018 The thread name is MainThread and end in Fri Jun 29 16:34:43 2018 The thread name is Thread-2 and end in Fri Jun 29 16:34:44 2018 The thread name is Thread-1 and end in Fri Jun 29 16:34:44 2018 The thread name is Thread-2 and start in Fri Jun 29 16:34:44 2018 The thread name is Thread-1 and start in Fri Jun 29 16:34:44 2018 The thread name is Thread-2 and end in Fri Jun 29 16:34:45 2018 The thread name is Thread-1 and end in Fri Jun 29 16:34:45 2018 '''
print("The thread name is {} and end in {}".format(threading.current_thread().name,ctime()))
# result ''' True The thread name is Thread-1 and start in Fri Jun 29 16:39:36 2018 True The thread name is Thread-2 and start in Fri Jun 29 16:39:36 2018 The thread name is MainThread and end in Fri Jun 29 16:39:36 2018 '''
defrun(self): for i in range(2): print("The thread name is {} and start in {}".format(threading.current_thread().name,ctime())) sleep(1) print("The thread name is {} and end in {}".format(threading.current_thread().name,ctime()))
if __name__ == "__main__": threads = [] for i in range(2): mt = MyThread() threads.append(mt)
for t in threads: t.start()
for t in threads: t.join()
''' The thread name is Thread-1 and start in Fri Jun 29 17:04:41 2018 The thread name is Thread-2 and start in Fri Jun 29 17:04:41 2018 The thread name is Thread-1 and end in Fri Jun 29 17:04:42 2018 The thread name is Thread-1 and start in Fri Jun 29 17:04:42 2018 The thread name is Thread-2 and end in Fri Jun 29 17:04:42 2018 The thread name is Thread-2 and start in Fri Jun 29 17:04:42 2018 The thread name is Thread-1 and end in Fri Jun 29 17:04:43 2018 The thread name is Thread-2 and end in Fri Jun 29 17:04:43 2018 '''