Laozizuiku 2019-10-21
题目有点忘了,大概是创建四个线程,要的输出结果差不多是这样,(没复习到线程,凉凉,补一下)
================= RESTART: /home/cmy/python/Internet/fuxi.py =================
开始线程 1 : 1
开始线程 1 : 2
开始线程 1 : 3
开始线程 1 : 4
开始线程 1 : 5
开始线程 2 : 6
开始线程 2 : 7
开始线程 2 : 8
开始线程 2 : 9
开始线程 2 : 10
开始线程 3 : 11
开始线程 3 : 12
开始线程 3 : 13
开始线程 3 : 14
开始线程 3 : 15
开始线程 4 : 16
开始线程 4 : 17
开始线程 4 : 18
开始线程 4 : 19
开始线程 4 : 20
代码
import threading
import time
threadlock=threading.Lock()
threads=[]
i=1
class myThread(threading.Thread):
def __init__(self,name):
threading.Thread.__init__(self)
self.name=name
def run(self):
threadlock.acquire()
print_out(self.name)
threadlock.release()
def print_out(name):
global i
count=0
while count<5:
print("开始线程",name,":",i)
count+=1
i+=1
print("")
thread1=myThread(‘1‘)
thread2=myThread(‘2‘)
thread3=myThread(‘3‘)
thread4=myThread(‘4‘)
thread1.start()
thread2.start()
thread3.start()
thread4.start()
threads.append(thread1)
threads.append(thread2)
threads.append(thread3)
threads.append(thread4)
for t in threads:
t.join()