zoukankan      html  css  js  c++  java
  • python:多线程

            python中提供thread 和 threading模块对多线程提供支持,其中threading模块是对thread模块的封装,多数情况下使用threading来进行多线程编程。

    一.使用threading.Thread在线程中运行函数

    # coding=utf-8
    import threading
    from time import ctime, sleep
    
    
    def music(func):
        for i in range(2):
            print '',i,'次听音乐!!!!'
            print 'I was listening to %s. %s' %(func,ctime())
            sleep(1)
    
    def move(func):
        for i in range(2):
            print '',i,'次看电影!!!'
            print 'I was at the %s!! %s' %(func,ctime())
            
    def run(x,y):
        s=x+y
        print '--------',s,'---------'
    
    
    #在线程中运行函数
    if __name__ == '__main__':
        threads=[]
        t1=threading.Thread(target=music,args=(u'爱情买卖',))
        threads.append(t1)
        
        t2=threading.Thread(target=move,args=(u'阿凡达',))
        threads.append(t2)
        
        t3=threading.Thread(target=run,args=(10,12))
        threads.append(t3)
        
        for t in threads:
            t.setDaemon(True)
            t.start()
       
        for t in threads:
            t.join()
        
        print 'all over %s' %ctime()

    二.继承threading.Thread 重载run方法

    #coding=utf-8
    import threading
    from time import sleep
    import time
    
    #继承threading.Thread类,重写run方法
    class mytheard(threading.Thread):
        def __init__(self,num):
            threading.Thread.__init__(self)
            self.num=num
            
        def run(self):
            print 'I am',self.num
            sleep(5)
            
            
    class Mythread(threading.Thread):
        def __init__(self,ssid,tname):
            threading.Thread.__init__(self,name=tname)
            self.ssid=ssid
             
        def run(self):
            x=0
            print x
            time.sleep(10)
            print self.ssid
            
    def example1():
        t1=mytheard(1)
        t2=mytheard(2)
        t3=mytheard(3)
        t1.start()
        t2.start()
        t3.start()
        
        
    def example2():
        t=Mythread(2,'t1')
        t.setDaemon(True)#设置该线程为守护线程
        t.start()
        print t.getName()
        t.setName('t2')
        print t.getName()#获取线程名
        print t.isAlive()#判断该线程是否还活着
        print t.isDaemon()#判断该线程是否为守护线程
        t.join()#阻塞主线程,直到线程t执行结束
        print 'work end!!!!'
            
    if __name__ == '__main__':
        example2()
  • 相关阅读:
    用数据泵技术实现逻辑备份Oracle 11g R2 数据泵技术详解(expdp impdp)
    用mysql实现类似于oracle dblink的功能
    统计1的个数
    转置字符串,其中单词内的字符需要正常
    经典排序之归并排序
    公共子序列与公共子串问题
    placement new (转)
    数组排序组合最小数字
    实现两个数相加不用四则运算
    操作系统中作业、线程、进程、内存管理、垃圾回收以及缓存等概念
  • 原文地址:https://www.cnblogs.com/dmir/p/5037007.html
Copyright © 2011-2022 走看看