zoukankan      html  css  js  c++  java
  • python多线程的基本使用

    python下实现多线程有两种方式:一种是通过函数的方式产生新的线程,另外一种是通过面向对象的方式实现

    通过调用thread模块中的start_new_thread()函数来产生新线程

    #!/usr/bin/env python
    #encoding:utf-8
    #author:zhxia
    import thread
    import time
    
    thread_count=0;
    def test(num,interval):
            for x in xrange(1,10):
               print 'current thread is:%d,and x is:%d'%(num,x)
               time.sleep(interval)
            thread.exit_thread()
    
    if __name__=='__main__':
            thread.start_new_thread(test,(1,1))
            thread.start_new_thread(test,(2,1))
            thread.start_new_thread(test,(3,1))
            #为了防止主线程在子线程之前退出,需要检测当前的子线程数目,直到所有的子线程执行完毕
            time.sleep(0.001) #必需sleep一下,否则取不到子线程的数目
            while thread._count()>0:
                    time.sleep(0.5)

    通过threading模块实现:

    #!/usr/bin/env python
    #encoding:utf-8
    #author:zhxia
    import time
    import threading
    import sys
    class test(threading.Thread):
            def __init__(self,num,interval):
                    threading.Thread.__init__(self)
                    self.thread_num=num
                    self.interval=interval
            def run(self):
                    for x in xrange(1,9):
                            print 'current thread is %d,and x is %d'%(self.thread_num,x)
                            time.sleep(self.interval)
    
    if __name__=='__main__':
            t1=test(1,1)
            t2=test(2,1)
            t3=test(3,1)
            t1.start();
            t2.start();
            t3.start();
  • 相关阅读:
    Git基本操作二
    Git基本操作一
    Mysql查询一
    接口的token验证
    Laravel模型的一些小技巧
    AOP编程思想实现全局异常处理
    5.4 RegExp类型
    5.4.1 RegExp实例属性
    5.4.2 RegExp实例方法
    5.4.3 RegExp构造函数属性
  • 原文地址:https://www.cnblogs.com/xiazh/p/2812666.html
Copyright © 2011-2022 走看看