python的学习之旅---信号量 定时器

把线程都创建好,等待执行。

current_thread().getName()

获取当前线程的线程名

from threading import Thread,Semaphore,current_thread
import time,random

sm=Semaphore(5)
def task():
    with sm:
        print('%s 正在上厕所' %current_thread().getName())
        time.sleep(random.randint(1,3))

if __name__ == '__main__':
    for i in range(20):
        t=Thread(target=task)
        t.start()

 

定时器

 from threading import   Timer

1 def hello(id):
2     print("hello, world",id)
3 
4 
5 t = Timer(1, hello,args=(30,))
6 t.start()  # after 1 seconds, "hello, world" will be printed

 

posted @ 2017-11-25 21:53  恩是的  阅读(194)  评论(0编辑  收藏  举报