Python 多线程

多线程

import threading
import time

def say(name):
print ('hello world,iam %s'%(name))
time.sleep(30)
print ('say finished%s'%(name))
res_list = []
for i in range(3):
t=threading.Thread(target=say,args=(i,))
#t.start()
#t.setDaemon(True)
res_list.append(t)
t.start()
#t.join()
for i in res_list:
i.join()
print ('Main Process finished')

 

import threading
import time

class MyThread(threading.Thread):
def __init__(self,name):
threading.Thread.__init__(self)
self.name = name
def run(self):
print ('hi , i am thread',self.name)
time.sleep(2)
for i in range(10):
t=MyThread(i)
t.start()
import time,threading
num = 100
l = threading.RLock()
def run (n):
global num
time.sleep(1)
l.acquire()
num -= 1
l.release()

for i in range(80):
t= threading.Thread(target=run,args=(i,))
t.start()
time.sleep(3)
print ("done:",num)
import  threading
import time
event = threading.Event()
def redLight():
while True:
event.set()
print ("\033[32;1mGreen 11111111 light!!!,all cars can pass.\033[0m")
time.sleep(15)
print ("\033[31;1mRed !!all 2222222222can car stop\033[0m")
event.clear()
time.sleep(5);
def car(name):
if event.is_set():
print ("green light now ,%s is 33333333333passing...."%(name))
else:
print ('i am car %s,waitin the 4444444444444red ligh'%(name))
event.wait() #check wait set
print ('\033[33;1m%s is passing the rea 555555555555555ligh\033[0m'%(name))
light=threading.Thread(target=redLight)
light.start()
while True:
for i in range(3):
t=threading.Thread(target=car,args=(i,))
t.start()
time.sleep(5)

 

posted @ 2016-04-28 14:19  FreeMan1  阅读(188)  评论(0编辑  收藏  举报