码迷,mamicode.com
首页 > 编程语言 > 详细

线程同步

时间:2015-11-06 00:19:01      阅读:235      评论:0      收藏:0      [点我收藏+]

标签:

# -*- coding: cp936 -*-
#python 27
#xiaodeng
#http://www.oschina.net/code/snippet_16840_1815



import threading,string,time


def print_time(threadName,delay,counter):
    while counter:
        time.sleep(delay)
        print %s:%s%(threadName,time.ctime(time.time()))
        counter-=1

class myThread(threading.Thread):

    def __init__(self,threadID,name,counter):
        threading.Thread.__init__(self)
        self.threadID=threadID#线程ID
        self.name=name#线程名字
        self.counter=counter#线程数量

    def run(self):
        #print self.name
        #获得锁,成功获得锁定后返回True
        threadLock.acquire()
        print_time(self.name,self.counter,1)#线程数量:1
        #释放锁
        threadLock.release()
        

#创建锁
threadLock=threading.Lock()
threads=[]

#创建新线程
thread1=myThread(1,thread1,1)
thread2=myThread(2,thread2,2)

#开启新线程
thread1.start()
thread2.start()

#添加线程到线程列表
threads.append(thread1)
threads.append(thread2)

#等待所有线程完成
for t in threads:
    t.join()

‘‘‘
thread1:Thu Nov 05 22:59:28 2015
thread1:Thu Nov 05 22:59:29 2015
thread1:Thu Nov 05 22:59:30 2015
thread2:Thu Nov 05 22:59:32 2015
thread2:Thu Nov 05 22:59:34 2015
thread2:Thu Nov 05 22:59:36 2015
‘‘‘

 

线程同步

标签:

原文地址:http://www.cnblogs.com/dengyg200891/p/4941177.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!