import threading
import time
import random
defreading():for i inrange(5):print("线程reading",i)
time.sleep(random.randint(1,2))defwriting():for i inrange(5):print("线程writing",i)
time.sleep(random.randint(1,2))print("开始住线程")
r=threading.Thread(target=reading)#运用函数为线程r
w=threading.Thread(target=writing)
r.start()#启动r线程
w.start()
w.join()#等待w线程结束才继续下一步# r.join()print("the end")
import threading
import time
import random
lock=threading._RLock()# 实例lock类
words=["a","b","c","d","e","f"]defincrease():global words
for count inrange(5):
lock.acquire()#print("A acquire")for i inrange(len(words)):for j inrange(i+1,len(words)):if words[i]>words[j]:
t=words[i]
words[j]=words[i]
words[j]=t
print("A",words)
time.sleep(1)
lock.release()defdecrease():global words
for count inrange(5):
lock.acquire()print("D acquire")for i inrange(len(words)):for j inrange(i+1,len(words)):if words[i]<words[j]:
t=words[i]
words[i]=words[j]
words[j]=t
print("D",words)
time.sleep(1)
lock.release()print("开始住线程")
a=threading.Thread(target=increase)
d=threading.Thread(target=decrease)
a.setDaemon(False)#子线程在后台运行
a.start()
a.join()
d.setDaemon(False)
d.start()print("the end")'''
结果
C:\Users\lxq\AppData\Local\Programs\Python\Python37\pythonw.exe E:/python/test/xm/xm/web/threadingcode.py
开始住线程
A acquire
A ['a', 'b', 'c', 'd', 'e', 'f']
A acquire
A ['a', 'b', 'c', 'd', 'e', 'f']
A acquire
A ['a', 'b', 'c', 'd', 'e', 'f']
A acquire
A ['a', 'b', 'c', 'd', 'e', 'f']
A acquire
A ['a', 'b', 'c', 'd', 'e', 'f']
the end
D acquire
D ['f', 'e', 'd', 'c', 'b', 'a']
D acquire
D ['f', 'e', 'd', 'c', 'b', 'a']
D acquire
D ['f', 'e', 'd', 'c', 'b', 'a']
D acquire
D ['f', 'e', 'd', 'c', 'b', 'a']
D acquire
D ['f', 'e', 'd', 'c', 'b', 'a']
'''
例码import threadingimport timeimport randomdef reading(): for i in range(5): print("线程reading",i) time.sleep(random.randint(1,2))def writing(): for i in range(5): ...