| 
 | 
 
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册  
 
x
 
- import time
 
 - import threading
 
  
- def music(name,times1):
 
 -     for i in range (times1):
 
 -         print('在听音乐 %s 时间 %s name:%s id:%s'%(name ,time.ctime() ,t1.getName() ,t1.ident))
 
 -         time.sleep(1)
 
  
- def movie(name,times2):
 
 -     for j in range (times2):
 
 -         print('在看电影 %s 时间 %s name:%s id:%s'%(name ,time.ctime() ,threading.Thread.getName(t2) ,t2.ident))
 
 -         time.sleep(1)
 
  
- t1 = threading.Thread(target=music,args=('虞兮叹',3))
 
 - t1.setName('music thread')
 
 - t2 = threading.Thread(target=movie,args=('魑魅魍魉',5),name='movie thread')
 
  
- t1.start()
 
 - t2.start()
 
  
- t1.join()
 
 - t2.join()
 
  
- print('任务完成啦 时间:%s'%time.ctime())
 
  复制代码 
都是这一段代码,运行的时候有的时候结果是对的,有的时候结果是错的。有大佬能给我指点一下迷津吗  
试试使用线程锁锁定打印函数,使同一时刻只能有一个线程print 
- import time
 
 - import threading
 
  
- # 实例化一个线程锁
 
 - alock = threading.Lock()
 
  
- def mprint(*args, **kwargs):
 
 -     # 获得锁
 
 -     alock.acquire()
 
 -     print(*args, **kwargs)
 
 -     # 释放锁
 
 -     alock.release()
 
  
- def music(name,times1):
 
 -     for i in range (times1):
 
 -         mprint('在听音乐 %s 时间 %s name:%s id:%s'%(name ,time.ctime() ,t1.getName() ,t1.ident))
 
 -         time.sleep(1)
 
  
- def movie(name,times2):
 
 -     for j in range (times2):
 
 -         mprint('在看电影 %s 时间 %s name:%s id:%s'%(name ,time.ctime() ,threading.Thread.getName(t2) ,t2.ident))
 
 -         time.sleep(1)
 
  
- t1 = threading.Thread(target=music,args=('虞兮叹',3))
 
 - t1.setName('music thread')
 
 - t2 = threading.Thread(target=movie,args=('魑魅魍魉',5),name='movie thread')
 
  
- t1.start()
 
 - t2.start()
 
  
- t1.join()
 
 - t2.join()
 
  
- print('任务完成啦 时间:%s'%time.ctime())
 
  复制代码 
 
 
 |   
- 
 
 
 
 
 
 
 
 |