本文介绍Python的多线程:
1、使用_thread模块
import _thread
import time
def print_time(threadName,delay):
count=1;
while count<5:
time.sleep(delay)
count+=1
print(threadName+time.ctime(time.time()))
try:
_thread.start_new_thread(print_time,("thread-1",2))
_thread.start_new_thread(print_time,("thread-2",4))
except Exception as e:
print("错误"+str(e))
while 1:
pass #空语句
2、使用threading模块
import threading
import time
def print_time(threadName,delay):
count=1;
while count<5:
time.sleep(delay)
count+=1
print(threadName+time.ctime(time.time()))
class myThread(threading.Thread): #继承Thread类,并重写run方法
threadId1=0
name1=""
def __init__(self,threadId,name):
threading.Thread.__init__(self) #调用父类
self.threadId1=threadId
self.name1=name
return
def run(self):
print("开始线程"+self.name1)
print_time(self.name1,2)
print("结束线程"+self.name1)
t1=myThread(1,"t1")
t2=myThread(2,"t2")
t1.start()
t2.start()
t1.join()
t2.join()
while 1:
pass
3、线程同步问题
import threading
import time
myList=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
class MyThread(threading.Thread):
threadName=''
flag=0 # 0表示做读,1表示做写1
threadLock=threading.Lock() #获取锁的对象
def __init__(self,threadName,flag):
threading.Thread.__init__(self) # 调用父类
self.threadName=threadName
self.flag=flag
def run(self):
print("线程开始"+self.threadName)
MyThread.threadLock.acquire() #获取锁
MyThread.change(self,self.threadName,self.flag)
MyThread.threadLock.release() #释放锁
print("线程结束"+self.threadName)
def change(self,threadName,flag):
if flag==0:
for a in myList: #读操作
print(a)
time.sleep(1)
elif flag==1:
co=0
while co<len(myList): #不断地把0变为1
myList[co]=1
#print(myList[co])
time.sleep(1)
co+=1
tMy1=MyThread("t1",0) #做读操作
tMy2=MyThread("t2",1) #做写操作
tMy1.start()
tMy2.start()
tMy1.join()
tMy2.join()
说明:线程tMy1去读List,线程tMy2去把List的内容改为1,;
当注释掉“获取锁”和“释放锁”的代码时,可以看到,tMy1读出了1,;当不注释,必须先读完才能再去修改