python 多线程

import threading
import time
from threading import Lock
class Mythread(threading.Thread):#继承与重写多线程
def __init__(self,num):
threading.Thread.__init__(self)
self.num=num
self.lock = Lock()

def run(self):
with self.lock:
self.func()


def func(self):
self.num += 1
time.sleep(1)
self.num -= 1
print('I am', self.num)




for i in range(100):
mythread = Mythread(0)
mythread.start()
print(mythread.isAlive()) #查看线程存活状态
mythread.join()



class mythread1(threading.Thread):
def __init__(self,threadname):
threading.Thread.__init__(self,name=threadname)
def run(self):
global event
if event.isSet():
event.clear() #清除
event.wait() #等待被设置
j=self.getName()
print(j)
else:
p=self.getName()
print(p)
event.set() #设置
event=threading.Event() #生成事件
event.set() #设置为True
t1=[]
for i in range(10):
t=mythread1(str(i))
t1.append(t)

for i in t1:
i.start()



posted @ 2018-05-02 12:43  盈波秋水泛清涛  阅读(139)  评论(0编辑  收藏  举报