zoukankan      html  css  js  c++  java
  • 线程同步

    # -*- 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
    '''
  • 相关阅读:
    (一)基础配置
    (一)Zookeeper全分布式搭建
    Go性能测试
    Go单元测试
    Go C连接(keep-alive/websocket) D连接 C轮询 D轮询
    Go UDP
    Go TCP 粘包
    Go Once用法 goroutine协程 chanel通道
    Go strconv包
    Go 反射reflect包
  • 原文地址:https://www.cnblogs.com/dengyg200891/p/4941177.html
Copyright © 2011-2022 走看看