threading 多线程使用

时间:2021-10-28 19:29:26
实例 1
import threading #线程
import time def Say(n):
print('Test %d' %n)
time.sleep(2) if __name__ == '__main__':
t1 = threading.Thread(target=Say,args=(10,)) #开一个线程,创建一个线程对象t1 target传递函数名 args传递参数
t1.start() t2 = threading.Thread(target=Say, args=(2,)) # 开一个线程,创建一个线程对象t2
t2.start() print('Done') 运行结果是下面3个打印结果同时出现,2秒后程序运行结束:
  Test 10
  Test 2
  Doen 实例2
import threading #线程
import time def Beijing(n):
print('Beijing time is start %s' % time.strftime('%Y-%m-%d %X', time.localtime()))
time.sleep(2)
print('Beijing time is over %s' % time.strftime('%Y-%m-%d %X', time.localtime())) def Shanghai(n):
print('Shanghai time is start %s' %time.strftime('%Y-%m-%d %X',time.localtime()))
time.sleep(5)
print('Shanghai time is over %s' %time.strftime('%Y-%m-%d %X',time.localtime())) if __name__ == '__main__':
t1 = threading.Thread(target=Beijing,args=(10,))
t1.start() t2 = threading.Thread(target=Shanghai, args=(2,))
t2.start() print('Done')
运行结果是:
  Beijing time is start 2018-05-29 17:29:25
  Shanghai time is start 2018-05-29 17:29:25       
  Done
  Beijing time is over 2018-05-29 17:29:27
  Shanghai time is over 2018-05-29 17:29:30
#Beijing Shanghai 同时执行 然后接着运行打印Done;3秒后开始打印Beijing结束时间,接着再过2秒打印Shanghai结束时间

实例3 for循环使用
import threading
from time import ctime,sleep
import time def ListenMusic(name): print ("Begin listening to %s. %s" %(name,ctime()))
sleep(3)
print("end listening %s"%ctime()) def RecordBlog(title): print ("Begin recording the %s! %s" %(title,ctime()))
sleep(5)
print('end recording %s'%ctime()) threads = [] t1 = threading.Thread(target=ListenMusic,args=('水手',))
t2 = threading.Thread(target=RecordBlog,args=('python线程',)) threads.append(t1)
threads.append(t2) if __name__ == '__main__':
for t in threads:
t.start()