python 多线程同步

来源:互联网 发布:星际战甲 解锁数据模块 编辑:程序博客网 时间:2024/05/14 09:59
<pre name="code" class="python"># coding=utf-8import threadingimport timeclass myThread (threading.Thread):    def __init__(self, threadID, name, counter):        threading.Thread.__init__(self)        self.threadID = threadID        self.name = name        self.counter = counter    def run(self):        print "Starting " + self.name       # 获得锁,成功获得锁定后返回True       # 可选的timeout参数不填时将一直阻塞直到获得锁定       # 否则超时后将返回False        threadLock.acquire()        print_time(self.name, self.counter, 3)        # 释放锁        threadLock.release()def print_time(threadName, delay, counter):    while counter:        time.sleep(delay)        print "%s: %s" % (threadName, time.ctime(time.time()))        counter -= 1threadLock = threading.Lock()threads = []for i in range(4):    # 创建新线程    thread = myThread(1, "Thread-" + str(i), 1)    # 添加线程到线程列表    threads.append(thread)    # 开启新线程    thread.start()# 等待所有线程完成for t in threads:    t.join()print "Exiting Main Thread"


                                             
0 0
原创粉丝点击